简体   繁体   English

如何在 reactjs 中映射 backgroundColor 键值?

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

I need to specify not in array values one Buttons should be in another color using a value in the map .我需要使用map中的值指定不在数组值中的一个 Buttons 应该是另一种颜色。
Is it any possible?有可能吗? I attached my code below.我在下面附上了我的代码。
CodeSandbox box Code 代码沙盒代码

You can use some function and check if index is available in queue, show red else blue.您可以使用某些功能并检查队列中是否有可用的索引,显示红色,否则显示蓝色。

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>
  );
}

Better solution:更好的解决方案:

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>
  );
}

I think you want to implement like this.我想你想这样实现。

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>
  );
}

This is codepen URL https://codesandbox.io/s/sleepy-darwin-4po149?file=/src/App.js:0-415这是 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