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

标签 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 属性从父级而不是子级获取值。

如何才能达到这个结果?

非常感谢 埃拉德

最佳答案

通过组件管理您的状态,并传递将更新状态的函数组件中的父组件

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

关于javascript - 在 React Native 中从父级更新子属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48783368/

相关文章:

javascript - 在 Javascript 中以秒为单位转换 getFullYear()

javascript - 无法在物理 iOS 设备 (9.3) 上启动 react-native

image - 使用 AWS Amplify 从 React Native 上传到 S3

react-native - 如何在react-native expo-cli中将app.js更改为另一个?

ios - React-Native navigation.addListener 不是函数

javascript - 拒绝访问 : Not authorized to perform sts:AssumeRoleWithWebIdentity

javascript - 将回调函数传递给原型(prototype)

javascript - 排序超过 10 行的 HTML 表格不起作用

javascript - IE 10, 11. 如何防止使用占位符的文本输入触发焦点输入事件?

javascript - 在 ref 属性中使用字符串文字已被弃用