反应 - 父母与子女之间的沟通

时间:2016-08-05 06:16:32

标签: javascript reactjs

这是我正在尝试实施的图片。 我需要父的handleChange函数(优化)来帮助它的所有子代更新它们的状态和ID。

  <Parent>

       constructor(props) {
          super(props);
          this.state = {
           child1State: null, child2State: null, child3State: null
          }
        }

        handleChange(){
          /* Add code to update the id of the changed element
           If bound attribute is present, numerize the e.target.value then update the id of the changed element]
           Previously this was with the child and handled using    
           this.setState({value: e.target.value});
           this.context.tree.select('app').set(this.props.id, (e.target.value));
           if (this.props.bound) this.context.tree.select('app').set(this.props.bound, Number(e.target.value));
           now this.props.id is undefined when I moved handleChange to the parent
          */

          this.setState({child1State: e.target.value});
        }

        onreset(){
          // here I would basically want the child1State and Child2State(select) to reset its value(would want something more optimised)
          this.setState({child1State: null});
        }

       <Child id="child1" value="this.props.child1State" bound="SelectedChild1" onChange={this.handleChange.bind(this)}></Child>
       <Child id="child2" value="this.props.child1State" onChange={this.handleChange.bind(this}></Child>
       <Child id="child3" value="this.props.child1State" onChange={this.handleChange.bind(this)}></Child>
       <Button>Reset Child1 and Child2<Button>
    <Parent>

这是孩子,它基本上是一个选择下拉列表。当Child1更新时,Child2应该具有与Child1相对应的值。如果Child1是City,那么Child2应该显示一个城市列表。如果Child1是国家,相应的国家/地区列表应该是显示在child2.and点击重置 - 这些选择框应该显示默认的禁用空值!Child3是另一个下拉列表,onChange应该更改其状态,绑定值到其id-什么都不做。

    <Child>
      <select id={this.props.id} value={that.props.value} onChange={this.props.onChange}>
       if(that.props.placeholder) return <option disabled selected>{that.props.placeholder}</option>
       {
         this.props.options.map(function(data, i) {
           return <option value={data.value} key={i}>{data.name{that.props.displayValue ? '(' + data.value + ')' : ''}</option>
        })
       }
      </select>
    </Child>

0 个答案:

没有答案