I'm having some issues pushing values from a form to an array that I'm mapping on the screen.
const ForumTopic = [ { title: "第一篇帖子", messages: "测试", author: "Dagger", count: 1, date: "02/16", }, ]; const [topic, setTopic] = useState(ForumTopic);
Store the ForumTopic in the state so that entries are added and displayed on the screen after clicking the submit button below.
const addTopic = (e) => { e.preventDefault(); setTopic([...topic, e.target.value]); }; <form onSubmit={addTopic}> 创建主题标题 <label htmlFor="title"> <input id="title"></input> </label> 编写您的消息 <label htmlFor="message"> <textarea id="message"></textarea> </label> <label htmlFor="author"> <input id="author" defaultValue="Dagger" hidden></input> </label> <label htmlFor="count"> <input id="count" defaultValue="1" hidden></input> </label> <label htmlFor="date"> <input id="date" defaultValue="02/16/2023" hidden></input> </label> <button type="submit"> 发布新消息 </button> </form>
This is my code and form. The purpose of the code is to push the value of each label in the form to create a new object in the topic
array. I want to store everything in a new object, with each tag's id
matching the name of each object (title, author, date, etc.), but for some reason I just get undefined mistake.
The problem lies in your addTopic function:
e.target.value is always undefined
To access the data you need to do this:
A simple way is to do this.
You need to use input's onChange to get the value you are getting.
Sample link: https://stackblitz.com/edit/react-8r9f8l?file=src/App.js