将不断变化的属性值设置为子状态变量

Setting a changing prop value to a child state variable

本文关键字:设置 状态 变量 属性 变化      更新时间:2023-09-26

假设我们有两个组件(Parent和Child),基本上我将Parents状态变量发送到子元素的输入元素以进行一些操作。类似…

 var Parent = React.createClass({
  getInitialState: function() {
    return {
      name: ''
    }
  },
  handleTextChange: function(e) {
    this.setState({
      name: e.target.value
    })
  },
  render: function() {
    return(
      <div>
      <input type="text" placeholder="Enter something" onChange={this.handleTextChange} />
      <Child name={this.state.name} />
      </div>
    )
  }
});

我的子组件是这样的…

var Child = React.createClass({
  getInitialState: function() {
    return {
      childName: ''
    }
  },
  componentWillReceiveProps: function(nextProps) {
    this.setState({
      childName: nextProps.name
    })
  },
  handleChildTextChange: function(e) {
    this.setState({
      childName: e.target.value
    })
  },
  render: function() {
    return(
      <div>
        <input type="text" onChange={this.handleChildTextChange} placeholder={this.props.name} />
        <h4>{this.state.childName}</h4>
      </div>
    )
  }
});

基本上我想做三件事

  1. 我的子组件的childName值最初应该设置为这个值parent的状态变量this.props.namename)
  2. 当我的Child的输入发生变化时,目标文本应该覆盖我的父的名字(this.props.name)
  3. 如果我的子输入为空,并且我的Parent的名字正在改变,则I我想让Child的组分状态变量childName等于改变来自父元素的道具(this.props.name)
有谁能帮我一下吗?

p。S:我的Child的组件目标文本不应该更新我的Parent的状态变量(名称),我的意思是,没有回调作为道具。

我认为你应该只在获得初始状态值时将状态设置为this.props.name,而不是每个componentWillReceiveProps示例。一旦子元素设置了自己的状态,该值只会在子元素中改变,而不会在父元素

中改变。

var Child = React.createClass({
  getInitialState: function() {
    return {
      childName: this.props.name,
      owned: false
    }
  },
  componentWillReceiveProps: function(nextProps) {
    // only do it if the state isn't owned by the child
    if (!this.state.owned) {
      this.setState({
        childName: nextProps.name,
        owned: false
      });
    }
  },
  handleChildTextChange: function(e) {
    this.setState({
      childName: e.target.value,
      owned: true
    });
  },
  render: function() {
    return(
      <div>
        <input type="text" onChange={this.handleChildTextChange} placeholder={this.props.name} />
        <h4>{this.state.childName}</h4>
      </div>
    )
  }
});
var Parent = React.createClass({
  getInitialState: function() {
    return {
      name: ''
    }
  },
  handleTextChange: function(e) {
    this.setState({
      name: e.target.value
    })
  },
  render: function() {
    return(
      <div>
      <input type="text" placeholder="Enter something" onChange={this.handleTextChange} />
      <Child name={this.state.name} />
      </div>
    )
  }
});
ReactDOM.render(<Parent />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container">
</div>