ReactJS字段不适用于动态字段

时间:2017-03-17 15:57:21

标签: reactjs

我有一个要求,我需要通过JSON动态创建字段。 我已根据需要创建了我的组件,并使用必填字段呈现页面。 但是这些字段处于不可编辑状态,即使我在InputField js文件中有一个onchange函数。以下是我的组件

中代码的一部分
onChange(event) {
        this.setState({
            [event.target.name]: event.target.value
        })
    }
    render() {
        return (
          this.props.screenField.fieldType === 'INPUT'
            ? <div className='form-group'>
                    <label htmlFor={this.props.screenField.name}>{this.props.screenField.label}:</label>
                    <input type={this.props.screenField.dataType === 'BOOLEAN'
                        ? 'checkbox'
                        : this.props.screenField.dataType}
                        name={this.props.screenField.name}
                        id={this.props.screenField.name}
                        placeholder={this.props.screenField.helpText}
                        required={this.props.screenField.isRequired}
                        value={this.props.screenField.value} className='form-control'
                        onChange={this.onChange.bind(this)}/>
                </div>
            : null
          )
    }

请在下面找到整个代码的网址。

https://github.com/yvsivateja/ReactJSApplications/tree/one/React-json-render

2 个答案:

答案 0 :(得分:1)

React的理念是道具应该是不可变的,并且如果你需要改变某些东西就使用状态。

将值绑定到不支持道具的状态。在构造函数中设置初始状态:

constructor(props) {
  super(props);
  this.state = {[this.props.screenField.name] : this.props.screenField.value};
}

绑定到状态:

value={this.state[this.props.screenField.name]} className='form-control'

答案 1 :(得分:0)

您可能希望将所有逻辑移出渲染函数,因为这通常是一种很好的做法。 render函数应该只包含以声明方式定义的组件,就像HTML一样。

您似乎缺少的一件事是用于评估JSX内部表达式的大括号。无论你现在在return语句中有什么,都应该包含在{}:

{this.props.... === 'INPUT' ? ... : ...}

正如我之前提到的,考虑将其移到外部渲染。也许你可以在返回之前使用if语句。另一个选择是将div提取到它自己的组件中(或者只是从辅助函数中返回它)。