我在React Native上有一个refs问题。这是我的代码的简化版本:
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 =&#34; index&#34;开头因此当我按下MyActionButton时,我会按预期看到日志,事情似乎有效:
'AB props', {flatlist: {A LOT OF STUFF HERE}}
但是,如果我将state.page更改为&#34; text&#34;然后回到&#34; index&#34;再次,当我按下MyActionButton时,我得到了:
'AB props', {flatlist: undefined}
我不确定为什么该道具未定义以及如何修复它以使其指向实际的FlatList。
答案 0 :(得分:0)
我不太喜欢,但我设法通过更改对getter功能的引用来实现它
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>
)
}
}
}