我试图在用户按下子级中的按钮后在父级中运行功能。

它在渲染子项时而不是在单击子项时运行该函数。

这是我的父母:

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}
      />
    }
  }
}


这是我的孩子

class Child extends Component {
  render() {
    const { changeStatus } = this.props;

    return (
      <TouchableOpacity onPress={changeStatus("go")}>
        <Text>Text</Text>
      </TouchableOpacity>
    );
  }
}

最佳答案

您应该传递一个函数,不要在render内部调用它。

class Child extends Component {
  render() {
    const { changeStatus } = this.props;

    return (
      <TouchableOpacity onPress={() => changeStatus("go")}>
        <Text>Text</Text>
      </TouchableOpacity>
    );
  }
}


UPD


  有没有一种方法可以在渲染器内部没有箭头功能的情况下进行


正常功能应该起作用。 onPress={onPress}其中function onPress() {...}。或者您可以使用ES5ivy方法onPress={changeStatus.bind(this, 'go')}

如果您根本不想在render中创建新函数,则可以这样做

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>
    );
  }
}

09-25 19:40