在React中更新对象元素的状态

时间:2018-06-12 08:01:32

标签: javascript reactjs

我正在做一个反应项目,我有一个数组中的对象我已将初始状态设置为

input: [
{item:'', label :'', codeBlock:''}
  ],

在onClick事件上,我设置了javaSript对象中元素值的状态,并使用下面的代码将它们推入输入数组中

Text(){

 const input = this.state.input;
 const item = <input type="text" placeholder="Enter text here!" 
className="InputDiv" onChange={this.handleTextChange.bind(this)}/>
 const codeBlock = <input type="text" placeholder="Enter text here!" 
 className="InputDiv"/>;
const label = this.state.label;
this.setState({input : input.concat({item, label, codeBlock})});
console.log(this.state.input)




}

现在我正在尝试更新onChange事件handleTextChange上label元素的值。我的意思是当前状态,在onChange事件上,只设置标签的值并更新状态。

请问我如何在React中做到这一点?

由于

2 个答案:

答案 0 :(得分:2)

这里尝试这样的事情......

&#13;
&#13;
class TodoApp extends React.Component {

  state = {
        input: [],
        currentItem: '',
        currentLabel: '',
        urrentCodeBlock: ''
  }

  handleInput = (e, label) => {
    // filling out currentState of your inputs
    this.setState({[label]: e.target.value})
  }
  
  clickHandler = () => {
    // creating copy of old array of inputs
    const newArr = [...this.state.input];
    // creating new Object that u defined
    const newObj = {
    	item: this.state.currentItem,
      label: this.state.currentLabel,
    	codeBlock: this.state.currentCodeBlock,
    }
    
    // pushing your new Obj to copy of old array
    newArr.push(newObj);
    
    // updateing state and setting input values to ''
    this.setState({
    	input: newArr,
      currentItem: '',
      currentLabel: '',
      currentCodeBlock: ''
    })
  }
  
  render() {
    let InputList = this.state.input.map((input, index) => (
    	<li key={index}> {input.item} - {input.label} - {input.codeBlock}</li>
    ))
    return (
      <div>
          <input type="text" placeholder="Item" value={this.state.currentItem} onChange={(e) => this.handleInput(e, 'currentItem')} />
          <input type="text" placeholder="Label" value={this.state.currentLabel} onChange={(e) => this.handleInput(e, 'currentLabel')} />
          <input type="text" placeholder="CodeBlock" value={this.state.currentCodeBlock} onChange={(e) => this.handleInput(e, 'currentCodeBlock')} />
          <button onClick={this.clickHandler}>SAVE</button>
          <hr/>
          <ul>
            {InputList}
          </ul>
      </div>
    )
  }
}

ReactDOM.render(<TodoApp />, document.querySelector("#app"))
&#13;
<div id="app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如果您的状态对象是数组,则必须从索引中选择正确的对象,创建重复的对象并分配新值,然后使用新值设置状态。

updateLabel=(text, index)=>{
 let allInputs = [...this.state.input];
 let selectedInput = {...allInputs[index]};
 selectedInput.label = text;
 allInputs[index] = selectedInput;
 this.setState({input:allInputs});
}