TaroProps
父组件传值 注意事项:
1、当传入的 obj 初始值是 null、 undefined、不存在
的时候(会报错误:TypeError:Cannot read property '0' of null
);
可以设置 Child.defaultProps = {obj: []}
定义初始值类型(注: 当设置初始值为null的时候,这个函数不会生效),就不会报错
2、父组件直接传入 clickTest1={this.clickTest1}
函数,子组件直接 onClick={clickTest1}
,(h5 与 小程序 不会报错, 也不会红线警告)
3、父组件直接传入 clickTest2={this.clickTest2}
函数,子组件通过 onHandleTest1 = () => {this.props.clickTest2()}
onClick={this.onHandleTest1}
调用,(h5 与 小程序 不会报错)
但是编辑器在调用传进来的函数处会有红线警示,
建议传给子组件函数前面添加 on 子组件 onHandleTest1 = () => {this.props.onClickTest2()}
4、父组件直接传入 onClickTest2={this.clickTest2}
函数
子组件通过 onHandleTest2() {this.props.onClickTest2()}
onClick={this.onHandleTest2}
调用 (小程序 不会报错, h5报错:Cannot read property 'props' of undefined
)
故 onClick={this.onHandleTest2.bind(this)}
要酱紫调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| import Taro, { Component } from '@tarojs/taro' import { View, Text } from '@tarojs/components'
class Child extends Component {
componentWillReceiveProps (nextProps) { console.log('componentWillReceiveProps',nextProps) }
onHandleTest1 = () => { console.log('onHandleTest1') this.props.onClickTest2() }
onHandleTest2() { console.log('onHandleTest2') this.props.onClickTest2() }
render() {
const { name, obj, clickTest1 } = this.props return ( <View> <Text>我是子节点</Text> <Text>{name}</Text> <Text>{obj[0]}</Text> <View><Text onClick={clickTest1}>点击clickTest1</Text></View> <View><Text onClick={this.onHandleTest1}>点击onHandleTest1触发父组件onClickTest2</Text></View> <View><Text onClick={this.onHandleTest2.bind(this)}>点击onHandleTest2触发父组件onClickTest2</Text></View> </View> ) } }
Child.defaultProps = { obj: [], }
export default Child
|