不确定如何从子组件更新父状态

时间:2018-08-09 14:21:54

标签: javascript reactjs

我有一个CreateTesterModal类,它具有位置状态。此类渲染一个表单组件,该组件会在该模式类中显示,如下所示: CreateTesterModal -> CreateTesterForm

CreateTesterModal

当用户单击Add位置链接时,将打开此新模式,其中包含位置表格 CreateTesterForm -> AddLocationModal -> AddLocationForm

AddLocationModal

我的问题现在是如何根据用户将在CreateTesterModal的子组件中输入的内容从主模式(AddLocationForm)更新我的位置状态? / p>

我是react的新手,确实需要这种逻辑才能在不使用redux的情况下工作。有人可以帮忙吗?


CreateTesterModal:

constructor(props) {
    super(props);
    this.state = {
      fields: {
        location: 'No Location Selected',
      }
    };
  }

  fieldChange(field, value) {
    this.setState(update(this.state, { fields: { [field]: { $set: value } } }));
  }

  updateLocation(newLocation) {
    this.setState({
      location: newLocation
    })
  }

  render() {
    return (
      <div>
        ...
        <div className={`modal-body ${styles['proj-modal-body']}`}>
          <CreateTesterCharacteristicForm
            fields={this.state.fields}
            onChange={this.fieldChange.bind(this)}
            onValid={() => handleSubmit(this.state.fields)}
            onInvalid={() => console.log('Error!')}
            updateLocation={this.updateLocation.bind(this)}
          />
        </div>
        ...
      </div>
    );
  }

CreateTesterForm:

<form>
    <div id={styles.locationField} className={`form-group ${styles.formGroup} ${styles.projName}`}>
              <label htmlFor="inputEmail3" className="col-sm-2 control-label">Location:</label>
              <div className="location">
                <label className="radio-inline">
                  &nbsp;
                  <Link to="#" data-toggle="modal" data-target="#addLocationModal">Add Locations</Link>
                </label>
              </div>
            </div>
    </form>
    <button
            className={`btn btn-primary text-white ${styles.saveBtn}`}
            onClick={e => {
              e.preventDefault();
              this.props.$submit(onValid, onInvalid);
            }}
          >
            Save
          </button>
<AddLocationModal />

AddLocationModal:

render() {
    return (
      <div id="newLocationModal">
        <AddLocationForm />
      </div>
    );
  }

AddLocationForm:

constructor(props) {
    super(props);
    this.state = {
      locations: [],
    };
  }
render() {
  return (
    <form id="modalForm" className="form-horizontal">
      <input
        type="text"
        class="form-control"
        id="location"
      />
      <div className={`modal-footer ${styles.modalFooter}`}>
        <button className={`btn btn-primary text-white ${styles.saveBtn}`}>
          Add More
        </button>
        <button
          type="button"
          className={`btn btn-default ${styles.cancelBtn}`}
          data-dismiss="modal"
        >
          Finish
        </button>
      </div>
    </form>
  );
}

2 个答案:

答案 0 :(得分:0)

基本上,您可以通过将处理程序从父级传递给子级来实现

  

注意:在这里,处理程序可以与this一起正常工作,因为它已被定义为箭头函数。如果使用类方法语法,请不要忘记将类的this绑定到该方法,否则this将引用触发事件的DOM元素(在这种情况下,button

class Parent extends Component {
  state = { location: null }

  updateLocation = location => {
    this.setState({ location })
  }

  render () {
    return <div><Child updateLocation={this.updateLocation} /></div>
  }
}

// Get the updateLocation function as a prop in your child component
const Child = props => {
  const { updateLocation } = props

  return <button onClick={() => updateLocation('someLocation')}>Some Location</button>
}

答案 1 :(得分:0)

您必须在子组件中定义一个函数,并使用您要更新的数据调用父组件中的另一个函数(作为props)。我没有您的代码,但应该是这样的: / p>

//child component
  ...class
  update = (data) =>{
   this.props.Parentupdate(data)      
    }
  //Parentupdate is the function in the parent class that will be passed down as props to the child comp.

//Inside the parent component
   update = (data) =>{
    this.setState({data etc etc})
}
//When rendering the child component
  <Child Parentupdate={this.update}/>
//This is passing the parent function to the child as a prop.