在React

时间:2019-09-20 12:53:51

标签: reactjs react-redux

我有这个简单的表格,我很难更改和获取该数组的状态。

状态已设置

this.state = {
            .....
        treatment:              [],
         .....
    }

更改时

onChange= (e) => {
    this.setState({
        [e.target.name]: e.target.value,
        error: ''
    })
}

单击包含一个数组元素的表单时,将调用该数组元素                     点击这里添加治疗                    

点击按钮后,JS就会弹出

$(document).ready(function (){
$('#addHidden').click(function(){
    var addtext = $('.hidden_box').html();
        $('#addHiddenBox').append(addtext);
});

$("#addHiddenBox").on("click", ".removeText", function () {
    $(this).closest(".boxAdded").remove();
});

});

并引入此隐藏元素

 <div className="hide hidden_box">           
      <div className="treatments col-sm-6 boxAdded">             
           <div className="form-group">
             <input className="form-control" type="text" placeholder="Treatment" name="treatment[]" value={this.state.treatment} onChange={this.onChange}/>
             <button className="btn btn-danger removeText" type="button"><i className="fa fa-times" aria-hidden="true"></i></button>
           </div>
        </div>
 </div>

我无法在此处设置治疗状态[]。状态变得一片空白。

2 个答案:

答案 0 :(得分:1)

您的情况下的

e.target.name将返回“ treatment[]”。注意方括号。

将其更改为此:

<input className="form-control" type="text" placeholder="Treatment" name="treatment" value={this.state.treatment} onChange={this.onChange}/>

答案 1 :(得分:1)

最后我解决了

JSX看起来像

<div className="form-group">
    <button className="btn btn-success" id="addHidden" type="button" onClick={(e)=>this.addTreatment(e)}><i className="glyphicon glyphicon-plus"></i> Click Here to add Treatment</button>
      <div id="addHiddenBox" className="row">
{
    this.state.treatment.map((treatment, index) =>{
       return(        
         <div className="treatments col-sm-6 boxAdded" key={index}>             
          <div className="form-group">
           <input className="form-control" type="text" placeholder="Treatment" name="treatment" value={treatment} onChange={(e)=>this.arrayChange(e, index)}  />
           <button className="btn btn-danger removeText" type="button" onClick={()=>this.arrayRemove(index)}><i className="fa fa-times" aria-hidden="true"></i></button>
          </div>
         </div>
      )
   })
}
 </div>
</div>

功能是:

this.state = {
        ...........
        treatment:              [],
        ..........
    }

addTreatment(){
    this.setState({treatment: [...this.state.treatment, ""]})
}

arrayChange(e, index){
    this.state.treatment[index] = e.target.value
    this.setState({treatment: this.state.treatment})
}

arrayRemove(index){
    this.state.treatment.splice(index, 1)
    this.setState({treatment: this.state.treatment})
}