Javascript 如何将参数返回给作为道具从父级传递的函数
我试图在用户按下子对象中的按钮后在父对象中运行函数 它在呈现子对象而不是单击子对象时运行函数 这是我的父母:Javascript 如何将参数返回给作为道具从父级传递的函数,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我试图在用户按下子对象中的按钮后在父对象中运行函数 它在呈现子对象而不是单击子对象时运行函数 这是我的父母: class Parent extends Component { constructor(props) { super(props); this.changeStatus = this.changeStatus.bind(this); } changeStatus(status) { console.log(status); } rend
class Parent extends Component {
constructor(props) {
super(props);
this.changeStatus = this.changeStatus.bind(this);
}
changeStatus(status) {
console.log(status);
}
render() {
return (
<Child
statusChange={this.statusChange}
/>
}
}
}
类父级扩展组件{
建造师(道具){
超级(道具);
this.changeStatus=this.changeStatus.bind(this);
}
更改状态(状态){
控制台日志(状态);
}
render(){
返回(
}
}
}
这是我的孩子
class Child extends Component {
render() {
const { changeStatus } = this.props;
return (
<TouchableOpacity onPress={changeStatus("go")}>
<Text>Text</Text>
</TouchableOpacity>
);
}
}
类子级扩展组件{
render(){
const{changeStatus}=this.props;
返回(
正文
);
}
}
您应该传递一个函数,使其不在渲染中调用
class Child extends Component {
render() {
const { changeStatus } = this.props;
return (
<TouchableOpacity onPress={() => changeStatus("go")}>
<Text>Text</Text>
</TouchableOpacity>
);
}
}
changeStatus!==statusChange
@DimitarChristoff是的,意识到有一个输入错误…我更改了它,但它仍然不起作用。如果渲染中没有箭头函数,有没有办法做到这一点?@ShinonChan是的。但是你仍然需要另一个函数作为onPress
处理程序传递。检查更新的答案。
class Child extends Component {
constructor(...args) {
super(...args)
this.changeStatus = this.changeStatus.bind(this)
}
changeStatus() {
this.props.changeStatus('go')
}
render() {
return (
<TouchableOpacity onPress={this.changeStatus}>
<Text>Text</Text>
</TouchableOpacity>
);
}
}