高阶组件,有状态组件和无状态组件的定义我就不再多说了,我对个理解的也不是太深入,仅仅是能熟练使用的状态,今天刚好有时间,就记录一下
首先这个高阶组件是由多个组件组合起来的,List,List组件中又包含了Banner组件,Banner是一个无状态组件,最后是一个Popup组件
我就只把Banner和Popup贴出来了
这是一个无状态的Banner组件,仅仅作为数据的展示,没有生命周期,没有转态管理,从父组件中,我们可以看到,父组件给他传了5个数据,在子组件中用吧这些传过来的东西当参数来接受
我们还可以这么写 const {data ,isIndex , autoplayInterval, autoplay, infinite} = props
const Banner = (props) => { let isIndex = props.isIndex ? true : false //是否是首页使用 let newHeight = props.height ? 300 : Dimensions.get('window').width*547/960 const {data ,isIndex , autoplayInterval, autoplay} = props return ({ props.data.length? props.data.map((item,index) => {return itemRende(item, index, isIndex, newHeight)}) : [false, false].map((item,index) => {return itemRende(item, index, isIndex, newHeight)}) } )}
接下来是一个有状态的Prupop,这个组件和父组件有交互,我们从父组件接受到了两个数据和两个函数
数据就不说了,我们是怎么使用接受到的函数呢?比如说我们从父组件接收到了closePopup这个函数,我们直接在需要的时候执行这个函数, this.props.closePopup(),我们还可以把一些参数也附带传过去,父组件就能接受到这个参数了
export default class Popup extends Component{ constructor(props) { super(props); this.state = { submitData:[], sumAmount:0, cartNumber:0 } } // 确定提交 _submit(closePopup){ this.props.closePopup() if (this.state.sumAmount) { if (this.props.setCart) { this.props.setCart(this.state.cartNumber) } this.setState({sumAmount:0}) this.props.dispatch({ type: 'cart/addProduct', payload: this.state.submitData }) this.setState({submitData:[]}) } } // 需要提交的数据 _submitData(id, price, count) { let data = this.state.submitData; let result = false; let amount = 0; if (data.length > 0) { data.forEach((item, index)=>{ if (item.skuId == id) { item.count = count amount = amount + price * count result = true }else { amount = amount +(item.price * item.count) } }) } if (!result) { data.push({skuId:id, price:price, count:count}) amount += price*count } this.setState({sumAmount: amount}) this.setState({submitData: data}) this.setState({cartNumber: data.length}) } // 商品列表 _itemRender(item, index){ return() } // 关闭时清空总价 closePopup(){ this.props.closePopup() this.setState({sumAmount:0}) this.setState({submitData:[]}) } render() { return ( {item.name} ¥{toFixedNumber(item.salesPrice)}/{item.unit} ) }} {this.props.data.map((item, index)=>{return this._itemRender(item, index)})} {this.state.sumAmount?'确认':'取消'} ¥({this.state.sumAmount?toFixedNumber(this.state.sumAmount):'0.00'})
在父组件中接受子组件传过来的值
文章有些乱,主要是开发的时候写到了,记录一下,说的不对请指正,谢谢