试图将数据从子组件传递到父组件

时间:2019-07-16 18:18:15

标签: reactjs

我试图在孩子的组件中获取输入,然后用它设置状态,然后将其传递给父对象,并在其中通过传递的数据设置状态-幸运的是,它发生了一些延迟:可以说输入是: 1”,则子状态为空-然后我添加“ 2”,因此子状态应为“ 12”,但其唯一的“ 1”-有人可以帮我弄清楚吗?

class PropertyCard extends React.Component{

  constructor(props){
    super(props);
    this.state={
        label:'',
        name:'',
        type:'',  
    };
    this.ChangeLabel = this.ChangeLabel.bind(this);
  }

  ChangeLabel = (updatedName) => {
    console.log("updatedName: "+updatedName);
    this.setState({label: updatedName});
    console.log(this.state.label);
  }

  CreateJson = () => {

    console.log(JSON.stringify(this.state));
  }

  render(){
    return(
      <div>
          <WizardField 
          label={'label'}
          type={'text'}
          name={this.state.label} 
          onUpdate={this} 
          handleChange={this.ChangeLabel}
          />

          <button 
          style={{marginTop:"10px" }}
          className="ui primary button"
          variant="primary"
          onClick={this.CreateJson}
          >Done!</button>
      </div>
    );
  }
 }

class WizardField extends React. Component{

  constructor(props){
    super(props);
    this.state={
      name:this.props.name
    };
    this.handleChange=this.handleChange.bind(this);
};

  handleChange = (e) => {
    this.setState({ name: e.target.value });
    console.log("state in child: "+this.state.name);
    this.props.handleChange(this.state.name);
    }

  render(){
    return(
      <div>
        <label>
          {this.props.label}:
        </label>
        <input 
          type={this.props.type}
          value={this.state.name} 
          onChange={this.handleChange}
        />
      </div>
    );
  }
}

2 个答案:

答案 0 :(得分:1)

要将数据从子级传递到父级,您可以将事件与回调函数一起使用: https://reactjs.org/docs/handling-events.html

答案 1 :(得分:1)

只需调用您通过道具传递的方法

function WizardField({label, name, handleChange, type="text") {
  return(
    <div>
      <label>
        {label}:
      </label>
      <input 
        type={type}
        value={name} 
        onChange={handleChange}
      />
    </div>
  );
}

您还需要更新handleChange处理程序。

handleChange = (e) => {
  this.setState({ name: e.target.value });
}
相关问题