如何将输入值添加到 React.js 中的状态?
how can i add input value to state in React.js?
我正在尝试获取输入值并在用户点击提交时将其推入状态,
但是我很困惑。
const App = () => {
const [category,setCategory] = useState([])
return (
<div>
<input type="text" name="" id="" />
<button type="submit" >Add</button>
</div>
);
}
export default App;
我尝试了很多方法,但我找不到任何解决方案。
你只需要有另一个存储当前输入值的状态变量。像这样:
const [categories, setCategories] = useState([]);
const [category, setCategory] = useState('');
const addCategory = () => {
setCategories([...categories, category]);
// after pushing the value, you may want to reset the input field
setCategory('');
};
...
<input value={category} onChange={(e) => setCategory(e.target.value)} />
<button onClick={addCategory}>Add</button>
试试这个
const App = () => {
const [category,setCategory] = useState([])
const addCategory = e => {
const newCategory = category
newCategory.push(e.target.previousElementSibling.value)
setCategory(newCategory)
}
return (
<div>
<input type="text" name="" id="" />
<button type="submit" onClick={addCategory}>Add</button>
</div>
);
}
export default App;
如果您不想使用 previousElementSibling
,请尝试使用这样的 useRef:
const App = () => {
const catRef = useRef(null)
const [category,setCategory] = useState([])
const addCategory = e => {
const newCategory = category
newCategory.push(catRef.current.value)
setCategory(newCategory)
}
return (
<div>
<input type="text" name="" ref={catRef} id="" />
<button type="submit" onClick={addCategory}>Add</button>
</div>
);
}
export default App;
当然你必须导入 useRef
我正在尝试获取输入值并在用户点击提交时将其推入状态, 但是我很困惑。
const App = () => {
const [category,setCategory] = useState([])
return (
<div>
<input type="text" name="" id="" />
<button type="submit" >Add</button>
</div>
);
}
export default App;
我尝试了很多方法,但我找不到任何解决方案。
你只需要有另一个存储当前输入值的状态变量。像这样:
const [categories, setCategories] = useState([]);
const [category, setCategory] = useState('');
const addCategory = () => {
setCategories([...categories, category]);
// after pushing the value, you may want to reset the input field
setCategory('');
};
...
<input value={category} onChange={(e) => setCategory(e.target.value)} />
<button onClick={addCategory}>Add</button>
试试这个
const App = () => {
const [category,setCategory] = useState([])
const addCategory = e => {
const newCategory = category
newCategory.push(e.target.previousElementSibling.value)
setCategory(newCategory)
}
return (
<div>
<input type="text" name="" id="" />
<button type="submit" onClick={addCategory}>Add</button>
</div>
);
}
export default App;
如果您不想使用 previousElementSibling
,请尝试使用这样的 useRef:
const App = () => {
const catRef = useRef(null)
const [category,setCategory] = useState([])
const addCategory = e => {
const newCategory = category
newCategory.push(catRef.current.value)
setCategory(newCategory)
}
return (
<div>
<input type="text" name="" ref={catRef} id="" />
<button type="submit" onClick={addCategory}>Add</button>
</div>
);
}
export default App;
当然你必须导入 useRef