javascript - React.js - 从 JSON 模式创建输入元素

标签 javascript json reactjs

我正在寻找有关在 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/

相关文章:

javascript - 带表单的 Bootstrap 弹出窗口

javascript - 如何在 javascript 中重新连接互联网后重新连接 Pubnub?

jquery - 使用 Jquery 获取 JSON 时出错

json - deleteByQuery 通过 XML 调用工作,但不通过 JSON 进行多条件查询

javascript - React this.props 不更新

javascript - 复选框组计算值

javascript - 如何在 iOS 中动态解析 JSON

javascript - 更改 firebase.database 内的变量

reactjs - Hook 不重新渲染组件

javascript - 如何使用javascript执行按钮点击操作