我使用reactjs制作输入字段,其末尾有一个“加号”,单击时,它会添加另一个输入字段...但我的问题是当我删除输入字段,然后再次添加时,它会不断增加...请检查我的代码并尝试...真的需要你们的帮助,提前感谢
addInput: function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div><input class="form-control categ-field" type="text" name="category[]" placeholder="Category" required> <a href="javascript:void(0);" class="remove_button" title="Remove field"><i class=" glyphicon glyphicon-minus-sign text-yellow"></i></a></div>'; //New input field html
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
}
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
},
render: (){
return React.createElement(
"div",
{ className: "field_wrapper" },
React.createElement("input", { type: "text", name: "category[]", className: "form-control categ-field", placeholder: "Category" }),
React.createElement(
"a",
{ className: "add_button", title: "Add field", href:"javascript:void(0);", onClick:this.addInput},
React.createElement("i", { className: "glyphicon glyphicon-plus-sign text-green" })
)
)
}
最佳答案
修改容器类并将其状态传递给另一个类:
var ContainerClass =
React.createClass({
getInitialState:function(){
return {
yourInputs: []
}
},
addInput:function(){
//use setState here
// TODO create an InputClass
this.setState({
yourInputs: this.state.yourInputs.push(InputClass)
})
},
removeInput: function(arrayId){
//TODO figure out how to pass arrayId as a prop
// and use setState to splice from yourInputs
},
render: function(){
return React.createElement(
"div",
{ className: "field_wrapper" },
React.createElement("input", { type: "text", name: "category[]",
className: "form-control categ-field", placeholder: "Category",
yourInputs: this.state.yourInputs},
React.createElement(
"a",
{ className: "add_button", title: "Add field", href:"javascript:void(0);",
onClick:this.addInput},
React.createElement("i", { className: "glyphicon glyphicon-plus-sign text-green" })
)
)
)
}
然后像上面一样传递 this.state.yourInputs
并映射 props 以返回输入列表:
React.createElement("div", null,
this.props.yourInputs.map(function(AnInput){
return React.createElement(AnInput, null, inputValue);
当您调用 setState
时,它将重新渲染并将新状态作为 props 传递给子级。
*注意:这只是一个建议,不是一个完整的解决方案,也不是关于如何使用 this.setState 的完全正确的解决方案,但是它确实指向正确的方向,其中 dom 不会被 React Virtual 之外的 jquery 操作统治。
为了删除,您可以传递一个数组 id 以及一个处理程序,然后将其从 yourInputs
关于javascript - Reactjs 添加和删除输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36614422/