React Native状态提升:如何在子组件通过onPress修改父组件状态
问题根因
- 子组件
ListHome中TouchableOpacity的onPress回调写法错误:() => this.goToMap.bind(this)仅会返回一个绑定了this的新函数,没有实际触发执行,这是点击只有触摸高亮、无切换效果的直接原因 - 父组件
Home中已经用箭头函数定义了goToMap方法,天然绑定了this上下文,传值时额外调用bind(this)属于冗余操作
修复代码
1. 修正Home组件的props传值
export default class Home extends React.Component { constructor(props) { super(props); this.state = { visible: true, whichComponentToShow: 'Screen1', }; } goToMap = () => { this.setState({ whichComponentToShow: 'Screen2' }); }; render(){ if(this.state.whichComponentToShow === 'Screen1'){ return( <View style={{backgroundColor: '#d1cfcf' ,flex: 1}}> {/* 直接传方法引用即可,不需要额外bind */} <ListHome renderMap = {this.goToMap} /> </View> ) } }
2. 修正ListHome组件的onPress逻辑
以下三种写法任选一种即可:
写法一:直接调用props传入的方法(最简洁)
<TouchableOpacity onPress={this.props.renderMap}> <View style={styles.conditionalMap}> <View style={{justifyContent: 'center', alignItems: 'center'}}> <Text style={{color: 'black', fontSize: scale(15)}}> Map </Text> </View> </View> </TouchableOpacity>
写法二:保留自定义goToMap方法,直接传方法引用
export default class ListHome extends React.Component { goToMap = () => { this.props.renderMap(); } render() { return ( <TouchableOpacity onPress={this.goToMap}> <View style={styles.conditionalMap}> <View style={{justifyContent: 'center', alignItems: 'center'}}> <Text style={{color: 'black', fontSize: scale(15)}}> Map </Text> </View> </View> </TouchableOpacity> ) } }
写法三:用箭头函数包裹执行
<TouchableOpacity onPress={() => this.goToMap()}>
修改完成后,点击ListHome组件内的Map按钮就会触发父组件的状态更新,实现和参考按钮完全一致的切换效果,符合状态提升的逻辑规范。
内容的提问来源于stack exchange,提问作者Justin Priede
相关产品推荐
相关产品推荐

