ReactJS 动态添加多个输入框

3

你好,我是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);
1个回答

0

如果你正在使用 redux-form,请查看带有 FieldArray 的示例,那应该会有所帮助。


嗨,如果我不使用Redux怎么办?这个还能在没有Redux的情况下实现吗? - Page F.P.T

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接