[英]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.