将表单数值推送到数组中。 (React)

huangapple go评论52阅读模式
英文:

Pushing form values to an array. (React)

问题

以下是您要翻译的部分:

I'm having some trouble pushing the values from my form to an array that I'm mapping on screen.

const ForumTopic = [
{
title: "First Post",
messages: "test",
author: "Dagger",
count: 1,
date: "02/16",
},
];

const [topic, setTopic] = useState(ForumTopic);

Storing ForumTopic in state so I can add entries and display on screen after I click the submit button below.

const addTopic = (e) => {
e.preventDefault();
setTopic([...topic, e.target.value]);
};

Create a topic title

Write your message





That's my code and form. The code is meant to push the values from each label in the form to create a new object inside the topic array. I want everything stored in a new object with the id of each label to match the names of each object (title, author, date, etc) but for some reason all I'm getting are undefined errors.

英文:

I'm having some trouble pushing the values from my form to an array that I'm mapping on screen.

const ForumTopic = [
  {
    title: "First Post",
    messages: "test",
    author: "Dagger",
    count: 1,
    date: "02/16",
  },
];

const [topic, setTopic] = useState(ForumTopic);

Storing ForumTopic in state so I can add entries and display on screen after I click the submit button below.

  const addTopic = (e) => {
    e.preventDefault();
    setTopic([...topic, e.target.value]);
  };

  <form onSubmit={addTopic}>
          Create a topic title
          <label htmlFor="title">
            <input id="title"></input>
          </label>
          Write your message
          <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">
            Post New Message
          </button>
        </form>

That's my code and form. The code is meant to push the values from each label in the form to create a new object inside the topic array. I want everything stored in a new object with the id of each label to match the names of each object (title, author, date, etc) but for some reason all I'm getting are undefined errors.

答案1

得分: 1

这是一个简单的做法。

你需要通过输入框的onChange事件获取到输入的值。

示例链接:https://stackblitz.com/edit/react-8r9f8l?file=src%2FApp.js

import React, { useState } from 'react';

const ForumTopic = [
  {
    title: 'First Post',
    messages: 'test',
    author: 'Dagger',
    count: 1,
    date: '02/16',
  },
];

export default function App() {
  const [topic, setTopic] = useState(ForumTopic);
  const [inputObj, setInputObj] = useState({
    title: '',
    messages: '',
    author: 'Dagger',
    count: 1,
    date: '02/16',
  });

  const handleChange = (event) => {
    setInputObj((curr) => ({
      ...curr,
      [event.target.name]: event.target.value,
    }));
  };

  const addTopic = (e) => {
    e.preventDefault();
    setTopic([...topic, inputObj]);
  };

  return (
    <>
      <form onSubmit={addTopic}>
        <label htmlFor="title">
          创建主题标题
          <input
            id="title"
            name="title"
            value={inputObj.title}
            onChange={handleChange}
          ></input>
        </label>
        <label htmlFor="message">
          编写您的消息
          <textarea
            id="message"
            name="messages"
            value={inputObj.messages}
            onChange={handleChange}
          ></textarea>
        </label>
        <label htmlFor="author">
          <input
            id="author"
            name="author"
            defaultValue="Dagger"
            hidden
          ></input>
        </label>
        <label htmlFor="count">
          <input id="count" name="count" defaultValue="1" hidden></input>
        </label>
        <label htmlFor="date">
          <input
            id="date"
            name="date"
            defaultValue="02/16/2023"
            hidden
          ></input>
        </label>
        <button type="submit">发布新消息</button>
      </form>
      {topic.map((item) => {
        return (
          <>
            <p>{item.title}</p>
            <p>{item.messages}</p>
            <p>{item.author}</p>
            <p>{item.count}</p>
            <p>{item.date}</p>
            <span>------------</span>
          </>
        );
      })}
    </>
  );
}
英文:

A simple way to do it is like this.

You need to obtain the value you are getting with an onChange in the input.

LINK to the example: https://stackblitz.com/edit/react-8r9f8l?file=src%2FApp.js

import React, { useState } from &#39;react&#39;;
const ForumTopic = [
{
title: &#39;First Post&#39;,
messages: &#39;test&#39;,
author: &#39;Dagger&#39;,
count: 1,
date: &#39;02/16&#39;,
},
];
export default function App() {
const [topic, setTopic] = useState(ForumTopic);
const [inputObj, setInputObj] = useState({
title: &#39;&#39;,
messages: &#39;&#39;,
author: &#39;Dagger&#39;,
count: 1,
date: &#39;02/16&#39;,
});
const handleChange = (event) =&gt; {
setInputObj((curr) =&gt; ({
...curr,
[event.target.name]: event.target.value,
}));
};
const addTopic = (e) =&gt; {
e.preventDefault();
setTopic([...topic, inputObj]);
};
return (
&lt;&gt;
&lt;form onSubmit={addTopic}&gt;
&lt;label htmlFor=&quot;title&quot;&gt;
Create a topic title
&lt;input
id=&quot;title&quot;
name=&quot;title&quot;
value={inputObj.title}
onChange={handleChange}
&gt;&lt;/input&gt;
&lt;/label&gt;
&lt;label htmlFor=&quot;message&quot;&gt;
Write your message
&lt;textarea
id=&quot;message&quot;
name=&quot;messages&quot;
value={inputObj.messages}
onChange={handleChange}
&gt;&lt;/textarea&gt;
&lt;/label&gt;
&lt;label htmlFor=&quot;author&quot;&gt;
&lt;input id=&quot;author&quot; name=&quot;author&quot; defaultValue=&quot;Dagger&quot; hidden&gt;&lt;/input&gt;
&lt;/label&gt;
&lt;label htmlFor=&quot;count&quot;&gt;
&lt;input id=&quot;count&quot; name=&quot;count&quot; defaultValue=&quot;1&quot; hidden&gt;&lt;/input&gt;
&lt;/label&gt;
&lt;label htmlFor=&quot;date&quot;&gt;
&lt;input id=&quot;date&quot; name=&quot;date&quot; defaultValue=&quot;02/16/2023&quot; hidden&gt;&lt;/input&gt;
&lt;/label&gt;
&lt;button type=&quot;submit&quot;&gt;Post New Message&lt;/button&gt;
&lt;/form&gt;
{topic.map((item) =&gt; {
return (
&lt;&gt;
&lt;p&gt;{item.title}&lt;/p&gt;
&lt;p&gt;{item.messages}&lt;/p&gt;
&lt;p&gt;{item.author}&lt;/p&gt;
&lt;p&gt;{item.count}&lt;/p&gt;
&lt;p&gt;{item.date}&lt;/p&gt;
&lt;span&gt;------------&lt;/span&gt;
&lt;/&gt;
);
})}
&lt;/&gt;
);
}

答案2

得分: 0

问题在于你的addTopic函数中:
e.target.value始终是未定义的

要访问数据,你需要这样做:

const addTopic = (e) => {
    e.preventDefault()

    const myData = {
        title: e.target.title.value,
        message: e.target.message.value
    }
    
    setTopic(prev => [...prev, myData])        
}
英文:

The problem is that on your addTopic function:
e.target.value are always undefined

to access the data you have to do:

const addTopic = (e) =&gt; {
e.preventDefault()
const myData = {
title: e.target.title.value,
message: e.target.message.value
}
setTopic(prev =&gt; [...prev, myData])        
}

huangapple
  • 本文由 发表于 2023年2月16日 18:35:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75471007.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定