如何在 React 中访问某个映射元素?

How to access a certain mapped element in React?

我有一个映射函数,其中 returns 个元素来自功能组件中的 JSON 回调。

我需要通过其属性从映射的回调中找到某个元素并为其着色。

如果没有 React.js,我可能会使用文档,但我知道最好使用变量引用。问题是我的元素可以从字符串访问并且没有永久顺序。我该怎么办?

我的代码示例:

   let x = [{name: 'elephant', symbol: 'e'}, {name: 'rabbit', symbol: 'r'}];

   let mapped = x.map(x =>
        <button
            title={x.name} // <- I want only: [title="elephant"]
        >
            {x.symbol}
        </button>
    )

    React.useEffect(() => {
          
    }, [])

这就是我使用文档的方式(没有 React.js):

document.querySelector('button[title="elephant"]').style.color = 'green';

有很多方法可以实现,一种是预先过滤(可以有多个匹配):

let mapped = x
  .find((x) => x.name === "elephant")
  .map((x) => <button title={x.name} style={{color: 'green'}}>{x.symbol}</button>);

您还可以查找(针对单个特定项目)然后使用值:

let specific = x.find((x) => x.name === "elephant");

// Then use it
<button title={specific.name} style={{color: 'green'}}>{specific.symbol}</button>;

它应该符合您的需要:

<button
  title={x.name} // <- I want only: [title="elephant"]
  style={x.name === 'elephant' ? { color: 'green'} : {}}
>
  {x.symbol}
</button>

或者,如果您想考虑向数组中 elephant 以外的对象添加样式的可能性,请考虑此模式。

let x = [
  {name: 'elephant', symbol: 'e', color: 'green'},
  {name: 'rabbit', symbol: 'r', color: 'red'},
  {name: 'dog', symbol: 'd'},
];

let mapped = x.map(x =>
  <button
    title={x.name}
    style={x.color ? {color: x.color} : undefined}
  >
    {x.symbol}
  </button>
)