React-Native之undefined is not an object
刚学习rn,有很多不理解的地方,常常会报undefined is not an object这个错,然后在不断的修改和试错的情况下 export default class Test extends Component {
constructor(props) {
super(props)
this.state = {
header: "我是header",_data: [
{key: 'a'},{key: 'b'},{key: 'c'},{key: 'd'},]
}
}
_header() {
return (
<Text style={{backgroundColor: "red",height: 100,}}>
{this.state.header}
</Text>
);
}
render() {
return (
<View>
<FlatList
ListHeaderComponent={this._header}//header头部组件
data={this.state._data}
renderItem={({item}) => <Text style={{alignSelf: "center",flex: 1,height: 30}}>{item.key}</Text>}
/>
</View>
);
}
}
报错如图 说是this.state.header这地方错误,刚接触这些很郁闷,引用state里面的值不都是这么引入的吗, export default class Test extends Component {
constructor(props) {
super(props)
this.state = {
header: "我是header",}
}
render() {
return (
<View>
<Text>{this.state.header}</Text>
</View>
);
}
}
完全是可以的,这让我这个初入rn的初学者头疼了,后来我想,会不会和这个this有关呢, export default class Test extends Component {
constructor(props) {
super(props)
this.state = {
header: "我是header",]
}
//将全局的this绑定到_header函数
this._header=this._header.bind(this)
}
_header() {
return (
<Text style={{backgroundColor: "red",height: 30}}>{item.key}</Text>}
/>
</View>
);
}
}
总结1、子组件指向的this属于子组件,与父组件无关 2、子组件不能去父组件更新状态 3、如果要在子组件更新父组件的状态,给子组件绑定父组件的this (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |