React.js - 从JSON模式创建输入元素 [英] React.js - Create input elements from JSON schema
问题描述
我正在寻找有关使用组件映射在React中动态创建JSON元素的最佳方法的建议。
I'm looking for advice on the best way to dynamically create elements from JSON in React using mapping with components.
我想我们可以将每个输入类型设置为一个单独的组件类,并构造传递 props
的元素并绑定更改。
I figure we can have each input type as a separate component class and construct the element passing in props
and bind the changes.
例如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中的每个项目?我在这里走在正确的轨道上吗?谢谢!
Any advice on the best way to iterate through (and validate) each item in the JSON? Am I on the right track here? Thanks!
推荐答案
您需要一个映射
的组件数据并返回 InputText
的集合。在这里,我称之为 Main
。
You need a component that map
s over the data and returns the collection of InputText
s. Here I've called it 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
并使用这些变量填写组件。
Now you can pick up those params in the component by deconstructing this.props.params
and using those variables to fill out the component.
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
这篇关于React.js - 从JSON模式创建输入元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!