reactjs - 单选按钮的反应组件
问题描述
我有一个包含许多输入和选择字段的表单。我使用输入和选择进行管理,但现在我正在尝试添加单选按钮和文本区域。在用户选择一个选项后,我发送的 json 没有更新来自无线电标头的值,并且选中的属性在按下时也没有更新。
这是单选按钮组件:
class RadioButton extends Component {
state = {
selectedOption: this.props.options[0].name,
};
handleOptionChange = (changeEvent) => {
this.setState({
selectedOption: changeEvent.target.value,
});
};
render() {
const { name, label, headline, options, ...rest } = this.props;
return (
<div>
<legend>{headline}</legend>
{options.map((option) => (
<div className="form-check">
<label className="form-check-label" htmlFor={name}>
<input
type="radio"
className="form-check-input"
name={name}
key={option._id}
value={option.value}
checked={this.state.selectedOption === option.name}
onChange={this.handleOptionChange}
></input>
<label>{option.name}</label>
</label>
</div>
))}
</div>
);
}
}
这是我在表单中呈现单选按钮的代码:
renderRadioButton(name, label, headline, options) {
const { data } = this.state;
console.log(name);
return (
<RadioButton
name={name}
label={label}
headline={headline}
value={data[name]}
options={options}
/>
);
}
这是渲染单选按钮的调用(此类派生表单类):
state = {
data: {
first_name: "",
last_name: "",
is_looking_for_job: "",
},
boolean_options: [
{ _id: 1, name: "Yes", value: "True" },
{ _id: 2, name: "No", value: "False" },
],
};
{this.renderRadioButton(
"is_looking_for_job",
"Looking for job",
"Looking for job",
this.state.boolean_options
)}
我希望有一个人可以帮助我。提前致谢!
解决方案
我认为这条线是问题所在:
checked={this.state.selectedOption === option.name}
将其更改为:
checked={this.state.selectedOption === option.value}
推荐阅读
- go - 当“go.mod”文件中没有指定A依赖时,Go使用什么依赖
- python - 如何查找文件中十个最常用单词的频率?
- python - 使用 python 从 Azure blob 读取 Json 文件?
- mysql - MySQL LOAD DATA LOCAL INFILE - 当分隔符不匹配时想要失败
- php - 在 WooCommerce 可变产品属性下拉选项中添加最小价格差异
- sql - 使用数组进行选择
- python - 如何通过夹具将测试状态传递给它的拆卸
- java - 如何在文本区域输入中保留格式?
- excel - Worksheet_Change 事件是否适用于 Office 2016 for Mac?
- ios - 从选择器视图(选择器轮)中获取选定的值