[英]React Native ref is undefined when re-rendering a component
我在React Native上的引用有问题。 这是我的代码的简化版本:
class Main extends React.Component {
constructor(props) {
...
this.refs = {};
}
render() {
if(this.state.page=="index") {
return(
<View>
<FlatList ref={flatlist => this.refs.flatlist = flatlist}> ... </FlatList>
<MyActionButton flatlist={this.refs.flatlist}/>
</View>
)
} else if (this.state.page="text"=){
return(
<Text> ... </Text>
)
}
}
}
class MyActionButton extends React.Component {
render(
return(
<ActionButton>
<ActionButtonItem onPress={() => {
console.log("AB props", this.props)
}} />
</ActionButton>
)
)
}
该应用程序以this.state.page =“ index”开头,因此当我按MyActionButton时,我看到了预期的日志,并且一切正常:
'AB props', {flatlist: {A LOT OF STUFF HERE}}
但是,如果我将state.page更改为“ text”,然后再次返回“ index”,则在按MyActionButton时会得到:
'AB props', {flatlist: undefined}
我不确定为什么该道具未定义以及如何对其进行修复以使其指向实际的FlatList。
我不太喜欢,但是我设法通过更改对吸气剂功能的引用来使其正常工作
class Main extends React.Component {
constructor(props) {
...
this.refs = {};
}
getFlatList() {
return this.refs.flatlist;
}
render() {
if(this.state.page=="index") {
return(
<View>
<FlatList ref={flatlist => this.refs.flatlist = flatlist}> ... </FlatList>
<MyActionButton flatlist={this.getFlatList.bind(this)}/>
</View>
)
} else if (this.state.page="text"=){
return(
<Text> ... </Text>
)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.