React Native:父组件触发子按钮组件onPress事件的问题
解决子组件触发父组件 onPress 事件的问题
嘿,我一眼就看到问题所在啦——你的子组件PrimaryButton压根没接住父组件传过来的onPress属性,也没把这个事件绑定到内部的可点击元素上,所以点击按钮当然没反应啦。
给你两个简单的修改步骤,马上就能搞定:
第一步:让子组件接收
onPress参数
把子组件的参数列表加上onPress,这样才能拿到父组件传过来的函数:const PrimaryButton = ({ text, onPress }) => {第二步:给
TouchableOpacity绑定onPress事件
在子组件的TouchableOpacity上添加onPress属性,值就是我们刚接收的onPress函数:<TouchableOpacity style={style.container} onPress={onPress}>
修改后的完整代码如下:
父组件
export class Home extends Component { constructor(props) { super(props); this.onPress = this.onPress.bind(this); } onPress = () => { console.log("Hey"); }; render() { return ( <View style={styles.container}> <PrimaryButton text={"Sign up"} onPress={this.onPress} /> </View> ); } }
子组件
const PrimaryButton = ({ text, onPress }) => { return ( <TouchableOpacity style={style.container} onPress={onPress}> <Text style={style.text}>{text}</Text> </TouchableOpacity> ); }; export default PrimaryButton;
这样修改之后,当你点击PrimaryButton时,就会触发父组件里的onPress函数,控制台就能正常打印"Hey"啦。
内容的提问来源于stack exchange,提问作者brunelli
相关产品推荐
相关产品推荐

