簡體   English   中英

ReactJS 動態輸入狀態

[英]ReactJS Dynamic input states

我需要添加一個“添加輸入”按鈕,該按鈕添加一個帶有一些輸入的<div> 這很好用,但如果我刪除一些元素(例如第一個元素),無論如何它都會刪除最后一個元素。

我正在閱讀這個問題,但我不知道如何將它帶到我的場景中。

我創建了這個 Codesandbox來查看“更大的圖景”。

主要思想是,每當您單擊“添加輸入”時,它都會將該div添加到addedInputs state 數組中:

function addInputElement(inputId) {
    const input = inputs[inputId];
    input.id = inputId;
    setAddedInputs([...addedInputs, input]);
    setSelectedValue("default");
    setAddInput(false);
}

當您寫入它的任何輸入時,它也會將其添加到 object inputValue中,其索引號與addedInputs數組相同。

function changeInputValue(element, index, value) {
    const iv = inputValue;
    if (iv[index]) {
      Object.assign(iv[index], { [element]: value });
    } else {
      Object.assign(iv, { [index]: { [element]: value } });
    }
    setInputValue(iv);
}

但是,當我從addedInputs中刪除輸入並嘗試從inputValue中刪除內容時,它會刪除正確的addedInputs元素,但不會刪除正確的inputValue元素:

function removeInputElement(index) {
    const filteredInputs = addedInputs.filter((input, i) => i !== index);
    setAddedInputs(filteredInputs);
    if (inputValue[index] !== undefined) {
      const ivs = inputValue;
      delete ivs[index];
      setInputValue(ivs);
    }
}

好吧,我不確定這是否是創建動態輸入狀態的正確方法,但是,無論如何,我的“錯誤”是我在從inputValues中刪除輸入值時做錯了。 那么,我做錯了什么?

如果您想要這里的整個代碼:

import React from "react";

const inputs = {
  "123": { name: "Simple text input", type: "text" },
  "456": { name: "Simple number input", type: "number" }
};

export default function App() {
  const [addedInputs, setAddedInputs] = React.useState([]);
  const [inputValue, setInputValue] = React.useState({});
  const [selectedValue, setSelectedValue] = React.useState("default");
  const [addInput, setAddInput] = React.useState(false);

  function addInputElement(inputId) {
    const input = inputs[inputId];
    input.id = inputId;
    setAddedInputs([...addedInputs, input]);
    setSelectedValue("default");
    setAddInput(false);
  }

  function removeInputElement(index) {
    const filteredInputs = addedInputs.filter((input, i) => i !== index);
    setAddedInputs(filteredInputs);
    if (inputValue[index] !== undefined) {
      const ivs = inputValue;
      delete ivs[index];
      setInputValue(ivs);
    }
  }

  function changeInputValue(element, index, value) {
    const iv = inputValue;
    if (iv[index]) {
      Object.assign(iv[index], { [element]: value });
    } else {
      Object.assign(iv, { [index]: { [element]: value } });
    }
    setInputValue(iv);
  }

  return (
    <div className="App">
      {addedInputs.map((input, index) => (
        <div key={index}>
          <h5>{input.name}</h5>
          <input
            placeholder="Title"
            type="text"
            value={
              inputValue[index] &&
              inputValue[index][input.id] &&
              inputValue[index][input.id].title
            }
            onChange={(e) => {
              changeInputValue("title", index, e.target.value);
            }}
          />
          <input
            placeholder="Description"
            type="text"
            value={
              inputValue[index] &&
              inputValue[index][input.id] &&
              inputValue[index][input.id].title
            }
            onChange={(e) => {
              changeInputValue("description", index, e.target.value);
            }}
          />
          &nbsp;
          <button
            onClick={() => {
              removeInputElement(index);
            }}
          >
            X
          </button>
        </div>
      ))}
      {addInput && (
        <select
          defaultValue={selectedValue}
          onChange={(e) => {
            addInputElement(e.target.value);
          }}
        >
          <option disabled value="default">
            Select an option
          </option>
          {Object.keys(inputs).map((key, index) => {
            const input = inputs[key];
            return (
              <option key={index} value={key}>
                {input.name}
              </option>
            );
          })}
        </select>
      )}
      <button
        onClick={() => {
          setAddInput(true);
        }}
      >
        Add input
      </button>
    </div>
  );
}

** 總體問題 **

  1. 您的代碼比它必須的要復雜一些,這是您的錯誤的第一個原因。 1a。 您有addedInputs state 變量,它跟蹤有關輸入的信息,但 1b。 ...您還有inputValue變量,它跟蹤多個輸入值。
  2. 您的命名約定(決定調用變量和鍵的方式)可能需要一些工作。 這里有兩個例子,雖然可能還有更多。 2a. 您的inputs變量。 輸入不一定有名稱、標題和描述。 您應該在您嘗試 model 的實際 object 之后將此變量命名為。 2b。 您的inputValue變量。 正如我上面所說,這個變量不應該存在,但如果你想要它,請在最后加上一個s ,因為它不跟蹤單個 value ,正如名字所暗示的那樣,而是你輸入中的所有值.

解決方案(針對您當前的問題)廢棄inputValue變量,並將每個“輸入”的值存儲在該輸入上。

這是一個工作示例,我在其中廢棄了 inputValue 變量,使事情變得更容易:

 import React from "react"; const inputs = { "123": { name: "Simple text input", type: "text" }, "456": { name: "Simple number input", type: "number" } }; export default function App() { const [addedInputs, setAddedInputs] = React.useState([]); const [selectedValue, setSelectedValue] = React.useState("default"); const [addInput, setAddInput] = React.useState(false); function addInputElement(inputId) { const input = inputs[inputId]; input.id = inputId; input.title = input.title || "A Default Title"; setAddedInputs([...addedInputs, input]); setSelectedValue("default"); setAddInput(false); } function removeInputElement(index) { const filteredInputs = addedInputs.filter((input, i) => i;== index); setAddedInputs(filteredInputs), } function changeInputValue(key, index. value) { const newAddedInput = {..,addedInputs[index]: [key]; value }. const newAddedInputs = [..;addedInputs]; newAddedInputs[index] = newAddedInput; setAddedInputs(newAddedInputs). } return ( <div className="App"> {addedInputs,map((input. index) => ( <div key={index}> <h5>{input.name}</h5> <input placeholder="Title" type="text" value={addedInputs[index] && addedInputs[index],title} onChange={(e) => { changeInputValue("title", index. e.target;value). }} /> <input placeholder="Description" type="text" value={addedInputs[index] && addedInputs[index],description} onChange={(e) => { changeInputValue("description", index. e.target;value); }} /> &nbsp; <button onClick={() => { removeInputElement(index). }} > X </button> </div> ))} {addInput && ( <select defaultValue={selectedValue} onChange={(e) => { addInputElement(e.target;value). }} > <option disabled value="default"> Select an option </option> {Object.keys(inputs),map((key; index) => { const input = inputs[key]. return ( <option key={index} value={key}> {input;name} </option> ); })} </select> )} <button onClick={() => { setAddInput(true); }} > Add input </button> </div> ); }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM