简体   繁体   English

处理React表单的状态

[英]Handling State of React forms

I have 2 components - MasterList and DetailComponent 我有2个组件-MasterList和DetailComponent

  1. Clicking a value in MasterList sends data to input element in DetailComponent. 单击MasterList中的值会将数据发送到DetailComponent中的输入元素。
  2. Detail component shows the prop passed 详细信息组件显示了通过的道具
  3. Detail component should be able to also update the input value 详细信息组件也应该能够更新输入值

Step 1 and 2 are working , not able to understand how to deal with Step 3. 步骤1和2正在运行,无法理解如何处理步骤3。

Following is the Sample code - Codesandbox 以下是示例代码-Codesandbox

You could initialize the form state with the props it receives. 您可以使用收到的道具来初始化表单状态。 The input can be assigned the value of the state. 可以为输入分配状态值。 Change in the input can change the state. 输入的改变可以改变状态。

A submit button could be added which would take the state values to update the data. 可以添加一个提交按钮,它将使用状态值来更新数据。 In this case you might want to remove the componentDidUpdate code and add it to your handleSubmit method. 在这种情况下,您可能想要删除componentDidUpdate代码并将其添加到handleSubmit方法中。

constructor(props) {
    super(props);

    this.state = {
      username: props.user.username
    };
  }

handleSubmit = () => {
    const { dispatch } = this.props
    let payload = {
      username: this.state.username
    };

    dispatch(updateUser(payload));
  };

updateState = (key, value) => {
    this.setState({
      [key]: value
    });
};

<input
  type="text"
  value={this.state.username}
  onChange={val => this.updateState("username", val)}
/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM