【发布时间】: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}
/>
{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