ReactJS动态添加多个输入字段
您好,我是React新手,我不知道如何使用React动态添加输入字段。 如果有人能帮我弄清楚如何绑定onclick来向表单动态添加另一个字段。 如何单击“添加”按钮,另一个选项输入将呈现ReactJS动态添加多个输入字段,reactjs,Reactjs,您好,我是React新手,我不知道如何使用React动态添加输入字段。 如果有人能帮我弄清楚如何绑定onclick来向表单动态添加另一个字段。 如何单击“添加”按钮,另一个选项输入将呈现 class AddPost extends Component { static contextTypes = { router: React.PropTypes.object }; appendInput() { var newInput = `inp
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);
class AddPost扩展组件{
静态上下文类型={
路由器: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,字段:{title,option}}=this.props;
返回(
问题:
{title.toucted&&title.error&&{title.error}
选项:
{option.toucted&&option.error&&{option.error}
选项:
{option.toucted&&option.error&&{option.error}
添加
this.appendInput()}>
单击我添加输入
);
}
}
函数验证(formProps){
常量错误={};
如果(!formProps.title){
errors.title=“需要标题”;
}
如果(!formProps.option){
errors.body=“选项是必需的”;
}
返回错误;
}
函数MapStateTops(状态){
返回{
职位:state.post
}
}
导出默认reduxForm({
表格:"邮政",,
字段:['title','body'],
验证:验证,
},mapstatetops,{addPost}(addPost);
如果您正在使用。使用签出示例,这应该会有所帮助。嗨,如果我没有使用redux怎么办?在没有redux的情况下,这仍然可以实现吗?