我正在寻找有关在 React 中使用组件映射从 JSON 动态创建元素的最佳方法的建议。
我认为我们可以将每个输入类型作为单独的组件类,并构造传入 props
的元素并绑定(bind)更改。
例如JSON:
{
"type": "text",
"name": "FirstName",
"class": "text",
"placeholder": "Enter first name"
},
{
"type": "text",
"name": "Surname",
"class": "text",
"placeholder": "Enter surname"
},
react :
class InputText extends React.Component {
constructor(props) {
super(props);
this.changeValue = this.changeValue.bind(this);
}
render() {
return (
<div className={className}>
<label htmlFor={this.props.name}>{this.props.title}</label>
<input
onChange={this.changeValue}
name={this.props.name}
type={this.props.type}
value={this.props.value}
/>
</div>
);
}
}
关于迭代(并验证)JSON 中每个项目的最佳方法有什么建议吗?我走在正确的轨道上吗?谢谢!
最佳答案
您需要一个能够映射
数据并返回InputText
集合的组件。这里我将其称为Main
。
class Main extends React.Component {
render() {
// Map over the data and return the completed component
// On each iteration pass in the object data as `params`.
// You can deconstruct this in the `InputText` component
return data.map((input, i) => {
return <InputText key={i} params={input} />
});
}
}
现在,您可以通过解构 this.props.params
并使用这些变量来填充组件来获取组件中的这些参数。
class InputText extends React.Component {
constructor(props) {
super(props);
this.changeValue = this.changeValue.bind(this);
}
changeValue() {
console.log('Placeholder to prevent bug');
}
render() {
// Use destructuring to grab the individual properties from params
const { type, name, classname, placeholder } = this.props.params;
// Use those properties in the returned component elements
return (
<div className={classname}>
<label htmlFor={name}>Test</label>
<input
onChange={this.changeValue}
name={name}
type={type}
placeholder={placeholder}
/>
</div>
);
}
}
<强> DEMO
关于javascript - React.js - 从 JSON 模式创建输入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47740235/