【问题标题】:React JS - Store radio button values into arrayReact JS - 将单选按钮值存储到数组中
【发布时间】:2018-01-23 01:06:55
【问题描述】:

我需要一些关于将单选按钮选中的值存储到数组中的帮助,我试过了,但我什么都做不了,这是我的代码 所以我想将选中的单选按钮传输并存储到一个数组中 我不知道该怎么办..

我的代码:

class Question extends Component {
  constructor() {
    super();
    this.state = { val: "" };
    this.onInput = this.onInput.bind(this);
  }
  //this.setState = {answers: {}};
  onInput(e) {
    this.setState({ val: e.target.value });
    console.log(this.state.data);
  }
  render() {
    var that = this; // Funny way to be able to access this from inside our iterator() function below.
    var iterator = this.props.questionChoices.map((choice, i) => {
      return (
        <div>
          <label className="container">
            <input
              className="input"
              key={i}
              type={that.props.questionType}
              name={that.props.questionID}
              value={choice}
              onChange={that.onInput}
            />
            &nbsp; {choice}
            <span className="checkmark" />
          </label>
        </div>
      );
    });
    return (
      <div className="row">
        <div className="form">
          <Paper zDepth={1}>
            <div className="h3">
              <h3 className="h3outter">
                {this.props.questionID} - {this.props.questionText}
              </h3>
              <p className="h3inner">{iterator}</p>
            </div>
          </Paper>
        </div>
      </div>
    );
  }
}

【问题讨论】:

  • 使用setState 更改状态后,您无法立即检查状态,因为setState 是一个异步进程。不过,setState 确实有一个可以使用的回调。
  • 您能否在您的问题中添加questionChoices 的示例?
  • { "questionID": 3, "questionType": "radio", "questionText": "L'unité du courant électrique est", "choices": ["L'Ampère", "Le Volt", "Le Watt"], "answer": "L'Ampère" },
  • 对不起布局,这是 questions.json 的开头,所以选择在那里
  • 我仍然不明白你的问题。我注意到的一件事是 this.setState({val: e.target.value}); 将是 this.setState({val: e.target.checked});

标签: javascript arrays reactjs radio-button


【解决方案1】:

好的。所以我稍微摆弄了一下你的代码并想出了这个。在render 中,它会遍历问题,而且(您缺少的部分)也会遍历单选按钮选项。

重要的部分在onInput 中,我们在其中获取现有状态并向其添加新的单选按钮值。如果问题已经得到回答,我们会删除现有的答案,并用新的答案替换它。

class Question extends React.Component {

  constructor() {
    super();
    this.state = { values: [] };
    this.onInput = this.onInput.bind(this);
    this.buildRadioButtons = this.buildRadioButtons.bind(this);
  }

  onInput(e) {
    const id = e.target.name;
    const answer = { id, answer: e.target.value };
    let answers;
    if (this.state.answers.some(answer => answer.id === id)) {
      answers = [...this.state.answers.filter(answer => answer.id !== id), answer];
    } else {
      answers = [...this.state.answers, answer];
    }
    this.setState({ answers }, () => console.log(this.state.answers));
  }

  buildRadioButtons(arr, type, id) {
    return arr.map((choice, i) => {
      return (
        <div key={i}>
          <input
          type={type}
          name={id}
          value={choice}
          onChange={this.onInput}
        />          
        <label>{choice}</label>
      </div>
     )
  })
 }

  render() {
    var iterator = this.props.questionChoices.map((question, i) => {
      const { choices, questionType, questionID, questionText } = question;
      return (
        <div key={i}>
          <h3>{questionText}</h3>
          {this.buildRadioButtons(choices, questionType, questionID)}
        </div>
      );
    });
    return (
      <div className="row">
        <div className="form">
          <div >
            <div className="h3">
              {iterator}
            </div>
          </div>
        </div>
      </div>
    );
  }
}

const questionChoices = [
  { "questionID": 3, "questionType": "radio", "questionText": "L'unité du courant électrique est", "choices": ["L’Ampère", "Le Volt", "Le Watt"], "answer": "L’Ampère" },
    { "questionID": 2, "questionType": "radio", "questionText": "What is your name?", "choices": ["Dave", "Nizar", "Bob"], "answer": "Nizar" }
]

ReactDOM.render(
  <Question questionChoices={questionChoices} />,
  document.getElementById('container')
);

Here's a working copy

【讨论】:

  • 在您的工作副本中,点击标签无法选择收音机
猜你喜欢
  • 2021-08-08
  • 1970-01-01
  • 2021-05-19
  • 2016-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多