React类父组件向子函数组件逐层传递state的实现问题求助
核心问题说明
- 函数组件不存在
this实例,你原Slider代码中写的this.goToMap会直接抛出未定义错误 - 你已经将Home组件的状态更新方法通过props逐层传递到了Slider组件,直接从函数组件的入参
props中调用对应方法即可 - 额外优化:你定义的
goToMap、goToList都是箭头函数,本身已经绑定了父级this,不需要再调用.bind(this),重复绑定会造成不必要的性能损耗
各文件修改示例
Home.js(仅修改透传props部分,其余逻辑保持不变)
export default class Home extends React.Component { constructor(props) { super(props) this.state ={ visible: true, whichComponentToShow: 'Screen1' }; } // 箭头函数自动绑定this,不需要额外bind goToMap = () => { this.setState({whichComponentToShow: 'Screen2'}) } goToList = () => { this.setState({whichComponentToShow: 'Screen1'}) } render(){ if(this.state.whichComponentToShow === 'Screen1'){ return( <View style={{backgroundColor: '#d1cfcf' ,flex: 1}}> {/* 移除多余的bind,直接传方法即可,如果需要传state值也可以在这里加props */} <ListHome renderMap = {this.goToMap} renderList = {this.goToList} homeVisible={this.state.visible} whichComponentToShow={this.state.whichComponentToShow} /> </View> ) } // 其余render逻辑保持你原有代码即可 } }
ListHome.js(仅修改透传props部分)
export default class ListHome extends React.Component { goToMap = () => { this.props.renderMap(); } goToList = () => { this.props.renderList(); } render() { return ( {/* 移除多余bind,透传方法,需要用到Home的state的话也一起透传 */} <Slider renderMap = {this.goToMap} renderList = {this.goToList} homeVisible={this.props.homeVisible} whichComponentToShow={this.props.whichComponentToShow} /> ) } }
Slider.js(核心修改)
const Slider = (props) => { // 可以先解构props,使用更方便 const { renderMap, renderList, homeVisible, whichComponentToShow } = props; const [active, setActive] = useState(false) let transformX = useRef(new Animated.Value(0)).current; // 原有动画逻辑保持不变 return ( {/* 直接调用props里的方法,不需要this */} <TouchableOpacity onPress={renderMap}> </TouchableOpacity> ); } export default Slider
内容的提问来源于stack exchange,提问作者Justin Priede
相关产品推荐
相关产品推荐

