繁体   English   中英

如何在 React.js 中将输入值添加到 state?

[英]how can i add input value to state in React.js?

我试图获取输入值并将其推入 state 当此人单击提交时,但我感到困惑。

const App = () => {
    const [category,setCategory] = useState([])
    return ( 
        <div>
            <input type="text" name="" id="" />
            <button type="submit" >Add</button>
        </div>
     );
}
 
export default App;

我尝试了很多方法,但找不到任何解决方案。

您只需要有另一个 state 变量来存储当前输入值。 像这样:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM