【问题标题】:Accessing key property of React component访问 React 组件的 key 属性
【发布时间】:2020-09-19 07:17:43
【问题描述】:
  1. 我映射了一系列位置
  2. 我想通过onClick访问组件的key
  3. 这是我的控制台.logconst addTo = (element) => {console.log(element);};
return (
    <>
      {data.map((item) => {

        return (
          <Marker key={Math.random()} position={item.fields.location}>
            <Popup>
              {item.fields.name} <br></br>
               <button
                onClick={() => {
                  addTo(item.fields.name);
                }}
              >Add 
              </button>
            </Popup>
          </Marker>
        );
      })}
    </>
  );
}

【问题讨论】:

  • key of the component 是什么意思?
  • key 是一个特殊的 react 属性。即使您将它作为道具传递,它也无法在组件中作为 props.key 访问。但是如果你需要它,你可以用不同的名字传递它:&lt;MyComponent key={123} myKey={123} /&gt; 并以props.myKey 访问它

标签: reactjs next.js react-props react-component react-leaflet


【解决方案1】:

来自React docs

键作为 React 的提示,但它们不会传递给您的组件。如果您需要在组件中使用相同的值,请将其作为具有不同名称的 prop 显式传递:

因此,您需要将密钥存储为变量或将其作为另一个道具名称传递

return (
    <>
      {data.map((item, index) => {
        const key = index;
        return (
          <Marker key={key} position={item.fields.location}>
            <Popup>
              {item.fields.name} <br></br>
               <button
                onClick={() => {
                  addTo(item.fields.name);
                  console.log(key)
                }}
              >Add 
              </button>
            </Popup>
          </Marker>
        );
      })}
    </>
  );
}

(此外,您应该考虑使用除Math.random 之外的另一个key,因为它会随着组件的每次渲染而变化)

如果你想访问元素本身,你应该考虑使用属性(即data-id={index})或者更好的是refThis answer 解释如何创建多个refs

【讨论】:

  • 这行得通,谢谢。我将使用 uuid 而不是数学随机数。
猜你喜欢
  • 2016-02-14
  • 1970-01-01
  • 2017-08-31
  • 2019-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-17
相关资源
最近更新 更多