首页 > 解决方案 > 如何使用回调函数将输入字段数据以 3 个不同组件的状态存储到我的第 4 个组件?

问题描述

我创建了三个组件和一个父组件。这三个组件各有支票票据信息字段。父组件有一个保存按钮。当单击保存按钮时,我想将数据从每个组件的输入字段数据发送到父元素中的状态。

标签: javascriptreactjs

解决方案


实现这一点的最简单方法是从包含所有这些组件的组件传递函数,以更新它们在父组件上的状态值。然后传递一个函数来处理复选框的值,也在父级上。这是一个示例,如果您需要澄清,请告诉我:

class CustomOne extends React.Component {
  render() {
    return (
    <label>
      field 1:
      <input
        name={this.props.inputName}
        type="text"
        value={this.props.inputValue}
        onChange={this.props.handleInputChange}
      />
      </label>
    );
  }
}

class CustomTwo extends React.Component {
  render() {
    return (
    <label>
      field 2:
      <input
        name={this.props.inputName}
        type="text"
        value={this.props.inputValue}
        onChange={this.props.handleInputChange}
      />
      </label>
    );
  }
}

class CustomThree extends React.Component {
  render() {
    return (
    <label>
      field 3:
      <input
        name={this.props.inputName}
        type="text"
        value={this.props.inputValue}
        onChange={this.props.handleInputChange}
      />
      </label>
    );
  }
}



class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue1: "",
      inputValue2: "",
      inputValue3: ""
    };

    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleClick = this.handleClick.bind(this);
  }

  handleInputChange(event) {
    const value = event.target.value;
    const name = event.target.name;

    this.setState({
      [name]: value
    });
  }

  handleClick() {
    console.log(this.state.inputValue1);
    console.log(this.state.inputValue2);
    console.log(this.state.inputValue3);
  }

  render() {
    return (
      <div>
        <form>
          <CustomOne
            inputName="inputValue1"
            inputValue={this.state.inputValue1}
            handleInputChange={this.handleInputChange}
          />
          <br />
          <CustomTwo
            inputName="inputValue2"
            inputValue={this.state.inputValue2}
            handleInputChange={this.handleInputChange}
          />
          <br />
          <CustomThree
            inputName="inputValue3"
            inputValue={this.state.inputValue3}
            handleInputChange={this.handleInputChange}
          />
        </form>
        <button onClick={this.handleClick}>Submit</button>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

编辑

我已经更新了我的答案,使每个都成为文本输入字段并将它们放入自己的自定义组件中。这是完全相同的概念,您只需将更新函数以及值传递给输入字段。全部存储在父级中。

要以不同的方式执行此操作,您需要使用一些用于状态管理的东西,例如 React 的 Context API:https ://reactjs.org/docs/context.html


推荐阅读