繁体   English   中英

如何使用钩子将数组添加到 React 中的空数组

[英]How to add an array to an empty array in React using hooks

我正在尝试创建一个随机名称生成器,用户可以在其中在文本框中输入一堆名称,然后它将 output 来自数组的单个名称。

到目前为止,我有以下内容:

 function App() { const [firstNames, setFirstNames] = useState(['']); const submitResults = (e) => { e.preventDefault(); console.log(firstNames.length); }; return ( <main> <form onSubmit={submitResults}> <div className="container"> <NameField htmlFor="first-selection" id="first-selection" title="Selection 1" value={firstNames} onChange={(e) => setFirstNames(e.target.value)} /> </div> </form> </main> ); }

但是当我 console.log firstNames.length时,我得到的是字符号。 例如,如果我提交[hello, there] ,我将得到 12 作为firstNames.length而不是 2。我尝试使用 onChange,但我仍然不确定如何更新 firstNames state 所以它添加数组正确。

您输入了一串以逗号分隔的名称,因此当您想将其作为数组处理时,您需要将字符串转换为字符串数组。

使用String.prototype.splitfirstNames state 用“,”分割得到一个数组。

firstNames.split(',').length

编辑 how-to-add-an-array-to-an-empty-array-in-react-using-hooks

function App() {
  const [firstNames, setFirstNames] = useState("");

  const submitResults = (e) => {
    e.preventDefault();
    console.log(firstNames.split(",").length);
  };

  return (
    <main>
      <form onSubmit={submitResults}>
        <div className="container">
          <input
            htmlFor="first-selection"
            id="first-selection"
            title="Selection 1"
            value={firstNames}
            onChange={(e) => setFirstNames(e.target.value)}
          />
          <button type="submit">Check Names</button>
        </div>
      </form>
    </main>
  );
}

暂无
暂无

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

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