簡體   English   中英

在React Native中從父級更新子級屬性

[英]Updating child property from parent in 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

通過parent組件管理state ,並pass將更新child組件中parent組件state的功能

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

你錯過了這個。 在setState子項中。 請檢查這是否不是問題。

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

應該

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM