react-navigation带参数跳转组件时bind()报错,求解决方案
看起来你遇到的问题本质不是添加跳转参数导致的,而是函数的this绑定不稳定引发的报错——Cannot read property 'bind' of undefined说明在执行this.onAccept.bind(this)时,this.onAccept找不到对应的方法,也就是当前this的指向不是你的组件实例。
你之前不带参数时能正常工作,只是巧合没有触发这个绑定问题,当你在onAccept里访问this.state的参数时,这种指向问题就暴露出来了。下面给你两种靠谱的解决办法:
方法一:在构造函数中提前绑定this
这种方式是类组件中绑定this的标准做法,能确保组件实例始终能访问到onAccept和onDecline方法:
修改你的构造函数,添加方法绑定:
constructor(props) { super(props); this.state = { showModal: false, selectedCity: 'Keelung', firstSliderValue: 18, secondSliderValue: 21 }; // 提前绑定this到组件实例 this.onAccept = this.onAccept.bind(this); this.onDecline = this.onDecline.bind(this); }
然后在render里的<Confirm>组件中,直接传递方法即可,不用再在render里bind:
<Confirm visible={this.state.showModal} onAccept={this.onAccept} onDecline={this.onDecline} onChangeValues={this.onChangeValues} > </Confirm>
方法二:用箭头函数定义类方法
箭头函数会自动绑定当前上下文的this,省去手动bind的步骤,代码更简洁:
把你的onAccept和onDecline改成箭头函数形式:
// 用箭头函数定义onAccept onAccept = () => { this.setState({ showModal: !this.state.showModal }); const { selectedCity, firstSliderValue, secondSliderValue } = this.state; console.log(selectedCity); console.log(firstSliderValue); console.log(secondSliderValue); this.props.navigation.navigate('MovieCloseTime', { selectedCity, firstSliderValue, secondSliderValue }); } // 同样修改onDecline onDecline = () => { this.setState({ showModal: false }); }
之后render里的<Confirm>组件同样直接传递onAccept={this.onAccept}即可。
补充:跳转参数的接收
等你解决绑定问题后,在MovieCloseTime组件里可以这样获取传递的参数(根据React Navigation版本调整):
- 如果是React Navigation v5+:
// 函数组件 const { selectedCity, firstSliderValue, secondSliderValue } = props.route.params; // 类组件 const { selectedCity, firstSliderValue, secondSliderValue } = this.props.route.params;
- 如果是React Navigation v4及更早版本:
// 类组件 const selectedCity = this.props.navigation.getParam('selectedCity'); const firstSliderValue = this.props.navigation.getParam('firstSliderValue'); const secondSliderValue = this.props.navigation.getParam('secondSliderValue');
内容的提问来源于stack exchange,提问作者Morton
相关产品推荐
相关产品推荐

