ReactJS动态添加多个输入字段

迈克尔·达席尔瓦(Michael DaSilva)

您好,我是React的新手,在尝试弄清楚如何使用React动态添加输入字段时迷失了方向。如果有人可以帮助我找出如何绑定onclick来向表单动态添加另一个字段。我如何单击添加按钮,另一个选项输入将呈现

class AddPost extends Component {
    static contextTypes = {
            router: React.PropTypes.object
};

    appendInput() {
        var newInput = `input-${this.state.inputs.length}`;
        this.setState({ inputs: this.state.inputs.concat([newInput]) });
    }

handleFormSubmit(formProps){
this.props.addPost(formProps);
this.context.router.push('/posts');
}
    render(){
      const {handleSubmit,fields:{title,option}} = this.props;
        return (
          <div className="row top-buffer">
          <div className="col md-auto">
                <form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
                <fieldset className="form-group">
                  <label>Question:</label>
                  <input {...title} className="form-control" placeholder="Enter question here"/>
                  {title.touched && title.error && <div className="text-danger">{title.error}</div>}
                  </fieldset>
                <fieldset className="form-group">
                  <label>Option:</label>
                  <input {...option} className="form-control" placeholder="Enter option"/>
                  {option.touched && option.error && <div className="text-danger">{option.error}</div>}
                </fieldset>
                    <fieldset className="form-group">
                        <label>Option:</label>
                        <input {...option} className="form-control" placeholder="Enter option"/>
                        {option.touched && option.error && <div className="text-danger">{option.error}</div>}
                    </fieldset>
                 <button className="btn btn-success">Add</button>
                </form>
              <button onClick={ () => this.appendInput() }>
                  CLICK ME TO ADD AN INPUT
              </button>
          </div>
          </div>
        );

    }

}

function validate(formProps){
const errors = {};
if(! formProps.title){
 errors.title = "Title is required";   
}
if(! formProps.option){
    errors.body = "Option is required";
}
return errors;
}

function mapStateToProps(state){
  return {
    posts:state.post
  }
}

export default reduxForm({
form:'post',
fields:['title','body'],
validate:validate,
},mapStateToProps,{addPost})(AddPost);
阮清(Thanh Nguyen)

如果您使用的是redux-form使用FieldArray检出示例,应该会有所帮助。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章