我不确定我做错了什么,这应该很容易!但是标题提到当我点击单选按钮时,他们要么没有被检查,要么在错误的时间被检查。
这里是代码的实时版本链接https://codesandbox.io/s/0wr7L3K5
这是我的 index.js
import React from 'react';
import { render } from 'react-dom';
import Radio from './Radio';
const styles = {
fontFamily: 'sans-serif',
textAlign: 'center',
};
const App = () => (
<div style={styles}>
<Radio voteName="yes" label="Yes" />
<Radio voteName="no" label="No" />
</div>
);
render(<App />, document.getElementById('root'));
这是 Radio.js
import React, {PropTypes} from 'react';
export default class VoteItem extends React.Component {
constructor() {
super();
this.state = {
selectedVote: ''
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
const newVal = event.target.value;
this.setState({
selectedVote: newVal,
});
}
render() {
return (
<div className="input">
<input
id={this.props.voteName}
type="radio"
value={this.props.voteName}
name="voteval"
onChange={this.handleChange}
checked={this.state.selectedVote === this.props.voteName}
/>
{this.props.label}
</div>
);
}
}
我已经看到了大部分 SO 问题,所有这些问题都建议删除event.preventDefault()
以进行检查,但正如您所看到的,我没有。
您应该将您选择的状态移动到 Radio.js 的超级视图。如:https : //codesandbox.io/s/1rXWKZLo0
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句