javascript - ReactJs - 迭代对象以创建表单字段
问题描述
我决定迭代一个数组并创建Form.Field
(semantic-ui)。这是我的静态代码,就像一个魅力:
export default class OrderChange extends Component<Props> {
constructor() {
super();
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
state = {}
handleChange = (e, { value }) => this.setState({ value })
render() {
<Form.Field>
<Radio
label='A'
name='radioGroup'
value='this'
checked={this.state.value === 'this'}
onChange={this.handleChange}
/>
</Form.Field>
<Form.Field>
<Radio
label='B'
name='radioGroup'
value='this1'
checked={this.state.value === 'this1'}
onChange={this.handleChange}
/>
</Form.Field>
});
我正在努力创建动态数据。首先,我创建了一个这样的对象:
const radios = [
{
name:'j',
value:1
},
{
name:'k',
value:2
}
];
然后,我试图对其进行迭代:
{radios.map(function (radio, index) {
return (
<Form.Field>
<Radio
label={radio.name}
name='radioGroup'
value='this'
checked={this.state.value === radio.value}
onChange={this.handleChange}
/>
</Form.Field>
);
})}
但是,我遇到了这个错误:
Cannot read property 'state' of undefined
在这一行:
checked={this.state.value === radio.value}
有什么建议吗?
解决方案
在您的情况下,state
声明为 aclass properties
而不是 a instance property
。
state = {} //class property will not available on this object
要么state
在构造函数中声明
constructor() {
this.state = {}; // now state available on this object
}
并且checked={this.state.value === radio.value}
会工作
或this
从此处删除。
checked={state.value === radio.value} // with class property state,it will work.
推荐阅读
- r - “对象‘我’未找到”for 循环
- perl - Perl:CAM::PDF 进行了更改,但这些并没有在最终文档中实现
- django - 从其他应用程序导入模型类而不会在 Django 中引起循环引用
- javascript - 如何在一行中获得 3 个 div?弹性不工作
- react-native - 使用 '--warning-mode all' 显示个别弃用警告
- html - 从模板中获取数据以发送电子邮件
- c# - 我只需要添加 4 个对象的属性
- android - 是否可以在 Firebase 中更改自动选择的用户属性
- java - Postman 在 SOAP 响应中返回 Null 值
- xcode - 如何从 C# 代码修改 XIB 中的属性