我有一組4個單選按鈕,我需要獲取所選按鈕的值。我應該確保用戶選擇了其中一個單選按鈕。這裏是我正在努力做到這一點:如何獲取ReactJS中的一組單選按鈕的值
export const ReportClass = React.createClass({
mixins: [React.addons.LinkedStateMixin],
getInitialState() {
return {
reason: "",
}
},
setError(id, msg) {
const err = this.state.errors;
err[id] = msg;
this.setState({errors: this.state.errors});
},
sendReport(event) {
event.preventDefault();
console.log(this.state.reason);
console.log(this.state.reason.value);
if (!this.state.reason) {
this.setError('reason', "Please choose one");
return;
}
},
render: function() {
return (
<div>
<form className="form-h" onSubmit={this.sendReport}>
<label forHtml='first'> first radio button </label>
<input ref='first' name='reason' type='radio' value='first' checkedLink={this.linkState('reason')} />
<label forHtml='second'> second radio button </label>
<input ref='second' name='reason' type='radio' value='second' checkedLink={this.linkState('reason')} />
<label forHtml='third'> third radio button</label>
<input ref='third' name='reason' type='radio' value='third' checkedLink={this.linkState('reason')} />
<label forHtml='forth'> forth radio button </label>
<input ref='forth' name='reason' type='radio' value='forth' checkedLink={this.linkState('reason')} />
<div className="col-sm">
<button type="submit" className="btn" onClick={this.sendReport}> Send</button>
</div>
</form>
</div>
);
}
});
的console.log(this.state.reason)
回報true
當按下其中一個按鈕選擇第二個,console.log(this.state.reason.value)
回報undefined
。那麼我怎麼才能知道哪一個是選擇的價值呢?
這是你所期望的嗎? http://jsbin.com/gupatu/edit?html,js,console,output –
聽取複選框更改事件,然後存儲該值,然後在提交時檢索此值? –
@MichaelRasoahaingo是的,這就是我想要的!請發佈它作爲答案:)謝謝 – Birish