[英]How can I store form input values as object of an array in another file in react using hooks?
我正在尝试存储正在以位于 FooterComponent.js 的表单中输入的用户的输入,并将该输入存储在位于 contact.js 的数组中,我试图通过在反应中使用钩子来实现这一点。
这是我的包含表单的 footerComponent.js:
const FooterComponent = () => { const [inputVal, setInputValue] = useState({ xemail: "", message: "", }); function handleChange(event) { console.log(event); const { name, value } = event.target; console.log(`Name: ${name} and value: ${value}`); setInputValue({...inputVal, [name]: value }); } const handleSubmit = (event) => { alert(`Email: ${inputVal.xemail} & Message: ${inputVal.message}`); event.preventDefault(); }; return ( <React.Fragment> <form className="form-center" onSubmit={handleSubmit}> <div className="footer-form-group"> <label htmlFor="exampleInputEmail1">Email*</label> <input type="email" className="form-control" id="exampleInputEmail1" name="xemail" defaultValue={inputVal.email} onChange={handleChange} required /> </div> <div className="footer-form-group"> <label htmlFor="exampleInputMessage">Message*</label> <br /> <textarea id="exampleInputMessage" cols="10" rows="5" name="message" defaultValue={inputVal.message} onChange={handleChange} required /> </div> <div className="footer-form-group"> <button type="submit" className="btn submit-btn"> SEND </button> </div> </form> </React.Fragment> ); };
我想将表单的新输入存储在表单数组中的contact.js中:
const contact[ { email: "abc@gmail.com", message: "Hello world 1", }, { email: "xyz@gmail.com", message: "Hello world 2", } ]
您可以使用上下文 API 访问组件外部的数据。 https://codesandbox.io/s/pensive-merkle-otwtl?file=/src/App.js
但是,要将数据文件写入磁盘,您需要能够访问文件系统的东西(例如 NodeJS)。 以下是有关在 Node 中处理文件的更多信息: https://nodejs.dev/learn/writing-files-with-nodejs
或者,您可以使用 localStorege 将此数据保存在浏览器的 memory 中: https://developer.mozilla.org/pl/docs/Web/API/Window/localStorage
然而,不幸的是,仅使用 React 将文件保存到磁盘是不可能的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.