簡體   English   中英

帶有 React Hooks 的動態狀態

[英]Dynamic States with React Hooks

我正在嘗試使用map() function 呈現一個數組,同時使用一些已建立的狀態為每個元素提供其自己唯一的類名(基於索引值)。 使用鈎子單擊時,元素應更改顏色。 我遇到了一個問題,其中className = {"header" + {index}.index}給出了正確的 state 名稱(header0、header1 等),但對應於字符串而不是使用相同名稱建立的 class 名稱。

const data = ["James", "John", "Jessica", "Jamie"];

export default function App() {
  const [header0, setHeader0] = useState("visable");
  const [header1, setHeader1] = useState("visable");
  const [header2, setHeader2] = useState("visable");
  const [header3, setHeader3] = useState("visable");

  const clicked = (index) => {
    if (index === 0) {
      setHeader0("invisible");
    } else if (index === 1) {
      setHeader1("invisible");
    }
    /*Is there an alternative like {setHeader + index} instead of this loop?*/
  };

  return (
    <div className="App">
      <h1>Sample Project</h1>
      {data.map((value, index) => (
        <h1
          className={"header" + { index }.index}
          onClick={() => {
            clicked(index);
          }}
        >
          {/* classname should be the state "header0" but right now its just a string */}
          Hello {value}!
        </h1>
      ))}
    </div>
  );
}

這是我正在嘗試的代碼沙箱,其中有一些出現問題的評論。 我是否以正確的方式解決這個問題? https://codesandbox.io/s/wispy-star-38qvw?fontsize=14&hidenavigation=1&theme=dark

編輯 wispy-star-38qvw

任何幫助是極大的贊賞!

您可以使用單個 state 陣列來獲得可見性。

此外,如果您將索引存儲在單擊元素的 HTML 數據集 ( data-index ) 中,則不需要為每個索引單獨設置閉包/函數。

 const data = ["James", "John", "Jessica", "Jamie"]; function App() { const [visibilities, setVisibilities] = React.useState(() => data.map((x) => true)); const handleClick = (event) => { const index = parseInt(event.currentTarget.dataset.index, 10); const newVisibilities = [...visibilities]; newVisibilities[index] =;newVisibilities[index]; setVisibilities(newVisibilities); }. return ( <div className="App"> {data,map((value? index) => ( <h1 data-index={index} onClick={handleClick} className={visibilities[index]: "selected", undefined}> Hello {value}? you are {visibilities[index]: "visible"; "hidden"}. </h1> ))} </div> ), } ReactDOM.render(<App />; document.querySelector("main"));
 .selected { background: lightgreen; } h1 { cursor: pointer; user-select: none; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.0/umd/react-dom.production.min.js"></script> <main></main>

您在單擊的 function 中聲明 2 arguments ,因此e是實際索引。

應該是

const clicked = (index) => {

恐怕這不是一個好方法,但你可以試試這個:

import React, { useState, useEffect } from "react";
import "./styles.css";

const data = ["James", "John", "Jessica", "Jamie"];

export default function App() {
  const headers = [];

  [headers[0], headers[1], headers[2], headers[3]] = [
    useState("visable"),
    useState("visable"),
    useState("visable"),
    useState("visable")
  ]; // each headers[index] is an array with [state, setState function]

  const clicked = (index) => {
    alert("clicked " + index);
    headers[index][1]("invisible");
    /*Is there an alternative like {setHeader + index} instead of this loop?*/
  };

  return (
    <div className="App">
      <h1>Sample Project</h1>
      {data.map((value, index) => (
        <h1
          className={headers[index][0]}
          onClick={() => {
            clicked(index);
          }}
        >
          {/* classname should be the state "header0" but right now its just a string */}
          Hello {value}!
        </h1>
      ))}
    </div>
  );
}

代碼筆: https://codesandbox.io/s/agitated-rain-o31ms

您可以更改將 state 構造為數組的方式,然后單擊 function 將通過索引使其不可見

const data = ["James", "John", "Jessica", "Jamie"];

export default function App() {
    const [headersVisible, setHeaderVisible] = useState(
        data.map(() => "visible")
    );

    const clicked = (index) => {
        setHeaderVisible(
            headersVisible.map((val, ix) => (index === ix ? "invisible" : val))
        );
    };

    return (
        <div className="App">
            <h1>Sample Project</h1>
            {data.map((value, index) => (
                <h1
                    key={index}
                    className={headersVisible[index]}
                    onClick={()=>clicked(index)}
                >
                    {/* classname should be the state "header0" but right now its just a string */}
                    Hello {value}!
                </h1>
            ))}
        </div>
    );
}

暫無
暫無

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

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