重新渲染组件时 React Native ref 未定义
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}
我不确定为什么该 prop 未定义以及如何修复它以使其指向实际的 FlatList。
我不是很喜欢,但我设法通过更改对 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>
)
}
}
}
我对 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}
我不确定为什么该 prop 未定义以及如何修复它以使其指向实际的 FlatList。
我不是很喜欢,但我设法通过更改对 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>
)
}
}
}