如何在react中处理多组单选按钮?

IT技术 reactjs
2021-05-06 03:00:05

所以我从后端获取了一些看起来像这样的数据

{"data":[{"status":1, "title":"Title 1"}, {"status":2, "title":"Title 2"}, {"status":1, "title":"Title 3"}, {"status":3, "title":"Title 4"}]}

它们将被映射到一个列表中,其中 status 的值决定了我在下面喜欢的 3 个单选按钮之一

{data.map(d => {
    return (
       <ListGroupItem>
          <Row>
            {d.title}
            <FormGroup>
            <Input
               type="radio"
               name={d.title}
               value="1"
               checked={d.status === 1}
               onChange={this.changeHandler}
             />
             Open
             </FormGroup>
             <FormGroup check inline>
                <Input
                  type="radio"
                  name={d.title}
                  value="2"
                  checked={d.status === 2}
                  onChange={this.changeHandler}
                />
                In-progress
              </FormGroup>
              <FormGroup check inline>
                 <Input
                    type="radio"
                    name={d.title}
                    value="3"
                    checked={d.status === 3}
                    onChange={this.changeHandler}
                 />
                 Closed
               </FormGroup>
           </Row>
        </ListGroupItem>
   );
})}

所以我的清单看起来像

Title 1      * open  0 in-progress  0 closed
Title 2      0 open  * in-progress  0 closed
Title 3      * open  0 in-progress  0 closed
Title 4      0 open  0 in-progress  * closed

(不是展示这一点的最佳方式)

现在我需要一个表单,以便在提交时选择的值将更新后端中的数据。我该怎么做呢?此外,我将如何处理 onChange 事件,因为现在即使我选择了一个单选按钮,也不会发生任何变化。

changeHandler = e => {
   //map the data to the proper place
}

submitHandler = e => {
   //submit the data
}

PS 我对 React 很陌生,所以这可能不是最好的方法。如果有更好的方法请告诉我。

1个回答

您的方法没问题,但是更改事件的处理方式不正确,因此状态不会更新。

起初,我认为这是状态的形状:

this.state = {
  data: [
    { title: "Title 1", status: 1 },
    { title: "Title 2", status: 2 },
    { title: "Title 3", status: 1 },
    { title: "Title 4", status: 3 }
  ]
};

然后状态可以更新如下(深受 Redux 启发)

handleChange = (event) => {
  this.setState({
    // the map method doesn't mutate the original array, it returns a new one
    data: this.state.data.map(item => {
      // iterate through the array to find the right item to update
      if (item.title !== event.target.name) {
        // not match, so we won't change anything here
        return item;
      } else {
        // match, we return the updated value
        return {
          title: item.title,
          // event.target.value is a string, but the state uses number so we have to convert it
          status: Number(event.target.value)
        };
      }
    })
  });
}

最后,您可以在处理提交事件时发送状态。