簡體   English   中英

在React中更新對象元素的狀態

[英]Update the state of an object element in React

我在一個React項目上工作,我在數組中有一個對象,我將初始狀態設置為

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中做到這一點?

謝謝

在這里嘗試這樣的事情...

 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")) 
 <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> 

如果狀態對象是數組,則必須從索引中選擇正確的對象,創建一個重復的對象並分配新值,然后使用新值設置狀態。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM