【问题标题】:How to access a certain mapped element in React?如何访问 React 中的某个映射元素?
【发布时间】:2020-12-25 15:44:25
【问题描述】:

我有一个 map 函数,它从功能组件中的 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';

【问题讨论】:

    标签: arrays reactjs callback attributes react-hooks


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      它应该适合您的需要:

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

      【讨论】:

        【解决方案3】:

        或者,如果您想考虑向数组中 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>
        )
        

        【讨论】:

          猜你喜欢
          • 2016-07-05
          • 2021-07-21
          • 2019-08-10
          • 2011-07-05
          • 2019-11-23
          • 1970-01-01
          • 1970-01-01
          • 2017-05-13
          相关资源
          最近更新 更多