我如何更新react.js中状态的选择选项

发布于 2025-01-11 02:14:05 字数 734 浏览 1 评论 0原文

我创建了一个输入,当您写一些内容并单击按钮时,值会添加到我们的状态中, 现在我正在尝试更新状态中的选择选项,如下所示:

const NewGroup = () => {
  const [group, setGroup] = useState([]);
  const addToGroup = (e) => {
    const newGroup = group;
    newGroup.push(e.target.previousElementSibling.value);
    setGroup(newGroup);
  };
  return (
    <div>
      <input type="text" name="" id="" />
      <button onClick={addToGroup}>submit</button>
      <div>
        <select name="" id="">
          {group.map((category) => {
            return <option value=''>{category}</option>;
          })}
        </select>
      </div>
    </div>
  );
};
export default NewGroup;

但什么也没发生。

I created an input, when you write something and click on the button, value adds to our state,
now I am trying to update select option from state like this:

const NewGroup = () => {
  const [group, setGroup] = useState([]);
  const addToGroup = (e) => {
    const newGroup = group;
    newGroup.push(e.target.previousElementSibling.value);
    setGroup(newGroup);
  };
  return (
    <div>
      <input type="text" name="" id="" />
      <button onClick={addToGroup}>submit</button>
      <div>
        <select name="" id="">
          {group.map((category) => {
            return <option value=''>{category}</option>;
          })}
        </select>
      </div>
    </div>
  );
};
export default NewGroup;

But nothing did happened.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

谎言月老 2025-01-18 02:14:05

您可以引入另一个 useState() 来写入 元素。当按下“提交”按钮时,您只需将 someText 推送到 group 数组。

const NewGroup = () => {
  const [group, setGroup] = useState([]);
  const [someText, setSomeText] = useState("");
  const addToGroup = (e) => {
    // Takes up all the present elements(of array group) and adds new element (search)
    let temp = [...group, someText];
    setGroup(temp);
  };
  return (
    <div>
      <input type="text" name="" id="" value={someText} onChange={(e) => { setSomeText(e.target.value); }} />
      <button onClick={addToGroup}>submit</button>
      <div>
        <select name="" id="">
          {group.map((category, index) => {
            return (
              <option key={index} value="">
                {category}
              </option>
            );
          })}
        </select>
      </div>
    </div>
  );
}

export default NewGroup;

以下是工作应用程序的链接 https://codesandbox。 io/s/boring-ptolemy-0cwzmi?file=/src/App.js

You can introduce another useState() for writing into <input> element. And when the Submit button is pressed, you only push the someText to the group array.

const NewGroup = () => {
  const [group, setGroup] = useState([]);
  const [someText, setSomeText] = useState("");
  const addToGroup = (e) => {
    // Takes up all the present elements(of array group) and adds new element (search)
    let temp = [...group, someText];
    setGroup(temp);
  };
  return (
    <div>
      <input type="text" name="" id="" value={someText} onChange={(e) => { setSomeText(e.target.value); }} />
      <button onClick={addToGroup}>submit</button>
      <div>
        <select name="" id="">
          {group.map((category, index) => {
            return (
              <option key={index} value="">
                {category}
              </option>
            );
          })}
        </select>
      </div>
    </div>
  );
}

export default NewGroup;

Here's the link to the working app https://codesandbox.io/s/boring-ptolemy-0cwzmi?file=/src/App.js

初见你 2025-01-18 02:14:05

首先,您不应该直接使用 DOM 来获取输入的值,而应该使用 Ref。

其次,问题是您直接改变组值而不是复制它。当你调用 setGroup 时,React 不会意识到有任何变化(因为之前的值等于当前值)。相反,您想要复制数组并添加新元素:

// Previously: const newGroup = group;
const newGroup = [...group];

这应该是让代码正常工作所需要做的全部事情。不过,我通过下面的内联注释对其进行了进一步简化和清理。

const NewGroup = () => {
    // Here's where our input will be stored so we can use it later (instead of querying the dom directly)
    const inputRef = React.useRef();
    const [group, setGroup] = React.useState([]);
    // Use React.useCallback so the function doesn't change on every render
    const addToGroup = React.useCallback((e) => {
        // We call setGroup with a function that returns the new group value. The first argument is the current group value. We return a new array by spreading the existing value and adding our new value
        setGroup((v) => [...v, inputRef.current.value]);
    }, []);
    return (
        <div>
            <input type="text" ref={inputRef} name="" id="" />
            <button onClick={addToGroup}>submit</button>
            <div>
                <select name="" id="">
                    {group.map((category) => {
                        return (
                            <option value="" key={category}>
                                {category}
                            </option>
                        );
                    })}
                </select>
            </div>
        </div>
    );
};

First, you should not be getting the value of your input by using the DOM directly, instead you should be using a Ref.

Secondly, the issue is that you're mutating the group value directly instead of copying it. When you call setGroup, React doesn't realize there was any change (because the previous value equals the current value). Instead you want to copy the array and add your new element:

// Previously: const newGroup = group;
const newGroup = [...group];

That should be all you have to do to get your code to work. However, I simplified and cleaned it up a little more with inline comments below.

const NewGroup = () => {
    // Here's where our input will be stored so we can use it later (instead of querying the dom directly)
    const inputRef = React.useRef();
    const [group, setGroup] = React.useState([]);
    // Use React.useCallback so the function doesn't change on every render
    const addToGroup = React.useCallback((e) => {
        // We call setGroup with a function that returns the new group value. The first argument is the current group value. We return a new array by spreading the existing value and adding our new value
        setGroup((v) => [...v, inputRef.current.value]);
    }, []);
    return (
        <div>
            <input type="text" ref={inputRef} name="" id="" />
            <button onClick={addToGroup}>submit</button>
            <div>
                <select name="" id="">
                    {group.map((category) => {
                        return (
                            <option value="" key={category}>
                                {category}
                            </option>
                        );
                    })}
                </select>
            </div>
        </div>
    );
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文