簡體   English   中英

如何在 reactjs 中映射 backgroundColor 鍵值?

[英]How to backgroundColor key values are map in reactjs?

我需要使用map中的值指定不在數組值中的一個 Buttons 應該是另一種顏色。
有可能嗎? 我在下面附上了我的代碼。
代碼沙盒代碼

您可以使用某些功能並檢查隊列中是否有可用的索引,顯示紅色,否則顯示藍色。

export default function App() {
  var b = ["one", "two", "three", "soma"];
  var que = [1, 2, 3];
  return (
    <div className="App">
      {b.map((text, index) => (
        <>
          <button
            style={{
              backgroundColor: que.some((value) => value === index + 1)
                ? "red"
                : "blue"
            }}
          >
            Button
          </button>
        </>
      ))}
    </div>
  );
}

更好的解決方案:

export default function App() {
  var b = ["one", "two", "three", "soma"];
  const set = new Set([(1, 2, 3)]);

  return (
    <div className="App">
      {b.map((text, index) => (
        <>
          <button
            style={{
              backgroundColor: set.has(index + 1) ? "red" : "blue",
            }}
          >
            Button
          </button>
        </>
      ))}
    </div>
  );
}

我想你想這樣實現。

import "./styles.css";

export default function App() {
  var b = ["one", "two", "three", "soma"];
  var que = [1, 2, 3];
  return (
    <div className="App">
      {b.map((text, index) => (
        <>
          <button
            style={{
              backgroundColor: que.filter((value) =>
                value === index + 1).length ? "red" : "blue"
            }}
          >
            Button
          </button>
        </>
      ))}
    </div>
  );
}

這是 codepen URL https://codesandbox.io/s/sleepy-darwin-4po149?file=/src/App.js:0-415

暫無
暫無

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

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