我有一个简单的表单,其中有几个单选按钮无法检查。每个按钮都附有一个更改事件,但仍然没有任何变化。我该怎么做才能捕获他们的数据,但表示输入已被选中?
表格
<script>
function checkForm() {
var elem = document.getElementById('myInput');
elem.value = elem.value.toLowerCase();
return elem.value.length > 0;
}
</script>
<form action="somewhere.php" method="POST" onSubmit="checkForm()">
<input id="myInput" type="text">
<button type="submit">Submit</button>
</form>
单选按钮
FormComponent = React.createClass({
propTypes: {
label: React.PropTypes.string,
onChange: React.PropTypes.func
},
handleEvent(e) {
let {onChange} = this.props;
console.log(e);
},
render() {
const {label} = this.props;
return (
<form className="lm-widget__form lm-flex-row">
<fieldset className="lm-flex-row__column lm-h-flex-50">
<RadioSet group='radio-group'
label={label}
radios={[
{
value: 'new',
checked: true,
changeEvent: this.handleEvent,
text: 'radio one'
},
{
value: 'old',
checked: false,
changeEvent: this.handleEvent,
text: 'radio two'
}
]}
/>
</fieldset>
</form>
)
}
});
答案 0 :(得分:2)
所以问题在于,您每次都会通过true
向其发送第一个单选按钮进行检查。
如果我们更改您的第一段代码以使用setState
,这应该有用。
FormComponent = React.createClass({
getInitialState() {
return {
checkedIndex: 0
};
},
propTypes: {
label: React.PropTypes.string,
onChange: React.PropTypes.func
},
handleEvent(index, e) {
this.setState({
checkedIndex: index
});
let {onChange} = this.props;
console.log(e);
},
render() {
const {label} = this.props;
const radios = [
{
value: 'new',
checked: false,
changeEvent: this.handleEvent.bind(this, 0),
text: 'radio one'
},
{
value: 'old',
checked: false,
changeEvent: this.handleEvent.bind(this, 1),
text: 'radio two'
}
];
radios[this.state.checkedIndex].checked = true;
return (
<form className="lm-widget__form lm-flex-row">
<fieldset className="lm-flex-row__column lm-h-flex-50">
<RadioSet group='radio-group'
label={label}
radios={radios}
/>
</fieldset>
</form>
)
}
});
另请注意,我们正在使用bind
来维护this
的{{1}}上下文并传入正确的索引。