这是我的反应代码,我想连接我的新表单输入到现有的状态数组上的按钮点击我试图用不同的方法连接状态数组,但它不工作,谁能帮助我在这方面:
import { useState } from 'react';
import './App.css';
let App = ()=>{
const [initial, addInitial] = useState('');
const [val, addVal] = useState(["Banana"]);
let changeHandler = (e)=>{
addInitial(e.target.value)
}
let addItem =()=>{
let newItem = initial;
}
return(
<div id="parent">
<div id="container">
<h1>To-Do List</h1>
<div id="sub1">
<input type="text" value={initial} onChange ={changeHandler} placeholder='Add a item' autoFocus/>
<button id="add" onClick = {addItem}>+</button>
</div>
<div id="sub2">
{
val.map((name, index)=>{
return(
<div id="cross" key={index}>
<button id="remove">❌</button>
{name}
</div>
)})
}
</div>
</div>
</div>
)
}
export default App;
在你的addItem()
方法中使用这个
let addItem = () => {
addVal(prevValues => [...prevValues, initial]);
};