如何使用单独的单选按钮表单元素在React元素上正确映射?

时间:2019-04-02 01:28:51

标签: javascript reactjs forms

我正在尝试创建卡元素,用户可以在图像上对“是”,“否”或“也许”进行投票。现在,它正像单选按钮一样读取一幅图像的90个选项,而不是30个具有3个选项的单个图像。如何在每张卡上映射,以便表单特定于图像?该数组将显示为

{ userChoices: {
  characterName[0]:choice.value,
  characterName[1]:choice.value,
  ....
}}
const choiceCard = characterData.map((character, key) =>
  <div className="col-sm-12 col-md-3" id="choiceCard" key={character.id}>
    <div id="choiceContent">
      <img src={character.statusImage}/>
      <div id="choice-inner" className="form">
        <span>{character.name}</span>
        <div class="form-check">
          <input 
           class="form-check-input" 
           type="radio" 
           name="yes" 
           id="yes" 
           value="yes"/>
          <label class="form-check-label" for="yes">
            Yes
          </label>
        </div>
        <div class="form-check">
          <input 
           class="form-check-input" 
           type="radio" 
           name="no" 
           id="no" 
           value="no"/>
          <label class="form-check-label" for="no">
            No
          </label>
        </div>
        <div class="form-check disabled">
          <input class="form-check-input" type="radio" name="maybe" id="maybe" value="maybe"/>
          <label class="form-check-label" for="maybe">
            Maybe
          </label>
        </div>
      </div>
    </div>
  </div>
);

1 个答案:

答案 0 :(得分:1)

您已接近要去的地方,这里只需要处理两件事:

  1. 将每组按钮与一个字符相关联。
  2. 跟踪每个角色的状态。

这是受控组件的自然使用案例。受控的单选按钮将如下所示:

<input
    key={someID}
    type="radio"
    value={choice}
    checked={this.state.choice === choice}
    onChange={() => this.handleChange(choice)}
/>

使用更改处理程序:

handleChange = newChoice => {
    this.setState({
        choice: choice
    });
}

(请参阅https://reactjs.org/docs/forms.html

将其应用于您的问题,最终会得到如下结果:

const choices = [
    "Yes",
    "No",
    "Maybe"
]

const choiceCard = characterData.map((character, key) => {
    return (
        <label key={character.id}>
            {character.name}
            {choices.map(choice => {
                return (
                    <input
                        key={choice}
                        type="radio"
                        value={choice}
                        checked={this.state.userChoices[key] === choice}
                        onChange={() => this.handleChange(choice, key)}
                    />
                );
            })}
        </label>
    );
});

以及以下更改处理程序:

handleChange = (choice, key) => {
    this.setState(prevState => ({
        userChoices: { ...prevState.userChoices, [key]: choice }
    }));
};

这是一个快速而肮脏的代码笔,您可以使用它来帮助您理解:https://codepen.io/anon/pen/axzMxm?editors=0010