在React Native中从父级更新子属性

时间:2018-02-14 09:12:27

标签: javascript react-native

我希望能够根据最后一个事件从父级和自身更新子组件属性。

例如:

class MyParent extends Component {
  state ={
    text:"";
  }
  render() {
    return (
      <View>
        <MyChild text={this.state.text} />
        <Button
          onPress={()=>this.setState({text:"parent"})}
          title="Update From Parent"
        />
     </View>
   );
  }
} 


class MyChild extends Component {
    state ={
      text:"";
    }

    componentWillReceiveProps(nextProps) {
    if (nextProps.text!== this.state.text) {
       this.setState({text:nextProps.text});
    }
}

render() {
    return (
      <View>
        {/* I want that the text field will be updated from the last event*/}
        <Text>{this.state.text}</Text>
        <Button
            onPress={()=>this.setState({text:"child"})}
            title="Update From Child"
        />
      </View>
   );
  }
} 

问题是每次调用setState时都会触发componentWillReceiveProps,因此text属性从父项而不是从子项中获取值。

我怎样才能获得这个结果?

非常感谢 ELAD

2 个答案:

答案 0 :(得分:1)

管理您的stateparent组件以及pass将更新state组件中parent组件的child的功能

class MyParent extends Component {

  constructor(props) {
    super(props);
    this.state = {
      text: "",
      updateParentState: (newState) => this.setState(newState)
    }
  }

  render() {
    let { text, updateParentState } = this.state;
    return (
      <View>
        <MyChild data={{ text, updateParentState }} />
        <Button
          onPress={() => updateParentState({ text: "parent" })}
          title="Update From Parent"
        />
      </View>
    );
  }
}


class MyChild extends Component {

  constructor(props) {
    super(props);
    this.state = {
      text: props.data.text
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.text !== this.state.text) {
      this.setState({ text: nextProps.data.text });
    }
  }

  render() {
    let { updateParentState } = this.props.data;
    return (
      <View>
        <Text>{this.state.text}</Text>
        <Button
          onPress={() => updateParentState({ text: "child" })}
          title="Update From Child"
        />
      </View>
    );
  }
}

答案 1 :(得分:0)

你错过了这个。在child中调用setState。请检查这不是问题。

data ChoiceFoo
    = FooA
    | FooB

data ChoiceBar
    = BarB
    | BarC

应该是

<Button
  onPress={()=>setState({text:"child"})}
  title="Update From Child"
/>