使用属性列表渲染React表单

时间:2016-07-14 11:23:35

标签: reactjs

首先,我想说我仍然在用React表面,所以如果这个问题看起来很愚蠢,那就道歉。

我想与某些字段建立联系表单,我想使用该字段呈现我的界面。就像这样:

名称 [____________]

电子邮件 [____________]

密码 [___________]

等...

我的反应代码(index.jsx):

import React from 'react';
import ReactDOM from 'react-dom';
import { fromJS } from 'immutable';
import { compose, createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import { Provider } from 'react-redux';
import { combineReducers } from 'redux-immutable';
import { logger } from './middleware';
import styles from './main.css';

var BillingLabel = React.createClass({
  render: function() {
    return (<b>First Name</b>);
  }
});

var BillingInput = React.createClass({
  render: function() {
    return (
        <form>
            <input
              type="text"
              placeholder="First name"
            />
        </form>
    );
  }
});

var BillingOption = React.createClass({
  render: function() {
    return (
        <div>
            <BillingLabel/>
            <BillingInput/>
        </div>
    );
  }
});

var OPTIONSFORM = [
  {labelOption: 'First Name', placeholder: 'First name'},
  {labelOption: 'Last Name', placeholder: 'Last name'},
  {labelOption: 'Website', placeholder: 'Store website'},
  {labelOption: 'Email', placeholder: 'Email contact'},
  {labelOption: 'Password', placeholder: ''},
  {labelOption: 'NIF', placeholder: ''},
];

ReactDOM.render(
  <BillingOption/>,
  document.getElementById('payment-system')
);

我这样想过界面:

BillingOption

  • BillingLabel
  • BillingInput

每个选项都由一个标签和一个输入框组成。

我希望接口循环遍历列表并构建所有BillingOption(在这种情况下,其中6个)。到目前为止,我只有它的第一个名字+输入。我怎样才能循环播放所有六个?

提前致谢。

1 个答案:

答案 0 :(得分:2)

您应该使用props来传递执行父子通信并在组件之间转换数据。这是fiddle

var BillingLabel = React.createClass({
  render: function() {
    return (<b>{this.props.label}</b>);
  }
});

var BillingInput = React.createClass({
  render: function() {
    return (
        <form>
            <input
              type="text"
              placeholder={this.props.placeHolder}
            />
        </form>
    );
  }
});

var BillingOption = React.createClass({
  render: function() {
    const form = this.props.options.map((option, i) => {
        return (
          <div key={i}>
              <BillingLabel label={option.labelOption}/>
              <BillingInput placeholder={option.placeholder}/>
          </div>
        )})
    return (
         <div>{form}</div>     
    );
  }
});

var OPTIONSFORM = [
  {labelOption: 'First Name', placeholder: 'First name'},
  {labelOption: 'Last Name', placeholder: 'Last name'},
  {labelOption: 'Website', placeholder: 'Store website'},
  {labelOption: 'Email', placeholder: 'Email contact'},
  {labelOption: 'Password', placeholder: ''},
  {labelOption: 'NIF', placeholder: ''},
];

ReactDOM.render(
  <BillingOption options={OPTIONSFORM}/>,
  document.getElementById('container')
);