如何从父级调用子级组件中的函数?

时间:2018-07-06 18:30:07

标签: reactjs react-native

因此,我的父组件具有一个“下一步”按钮。当我点击此“下一步”按钮时,我希望它在子级中调用将数据传递到全局状态的函数。最好的方法是什么?这是一些伪代码:

<Parent />


this.state{
  change: 'Two'
}

functionOne(){
  this.setState({
    change: 'One'
  })
}

render(){
  return(
    <View>
      <TouchableOpacity 
        onPress={ () => this.functionOne() }>
      </TouchableOpacity>
    </View>
  )
}


<Child />

this.state {
  data1: "I"
  data2: "WANT"
  data3: "THIS"
}

thisOne(){
 this.props.toGlobal(this.state)
}

2 个答案:

答案 0 :(得分:0)

您可以在子组件上设置ref并从父组件调用该函数。

// Parent
render(){
  return(
    <View>
      <TouchableOpacity 
        onPress={ () => this.child.functionOne() }>
      </TouchableOpacity>
      <Child ref={child => this.child = child} />
    </View>
  )
}

答案 1 :(得分:0)

您应该将处理程序传递给子代,然后使用您希望更新的任何值作为参数在父代上调用它。

示例:

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      change: 'Two'
    };

    this.toGlobal = this.toGlobal.bind(this);
  }

  toGlobal(values) {
    // update global state with value
  }

  render() {
    return(
      <Child
        toGlobal={this.toGlobal} />
    );
  }
}

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.state {
      data1: "I"
      data2: "WANT"
      data3: "THIS"
    };

    this.thisOne = this.thisOne.bind(this);
  }

  thisOne() {
    this.props.toGlobal(this.state);
  }

  render() {
    return (
      <div>
        <button
          onClick={this.thisOne} />
      </div>
    );
  }
}
相关问题