React组件的访问键属性

问题描述 投票:1回答:1
  1. 我通过一系列位置进行映射
  2. 我想通过onClick访问组件的键
  3. 这是我的console.log const 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>
        );
      })}
    </>
  );
}
reactjs next.js react-props react-component react-leaflet
1个回答
0
投票

React docs

键只是React的提示,但不会传递给您的组件。如果您的组件中需要相同的值,则将其作为道具以不同的名称显式传递:

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

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

((您还应考虑使用key以外的其他Math.random,因为随着组件的每次渲染都会改变)

如果要访问元素本身,则应考虑使用属性(即data-id={index})或更佳的ref

© www.soinside.com 2019 - 2024. All rights reserved.