访问 React 组件的 key 属性

Accessing key property of React component

  1. 我通过一组位置进行映射
  2. 我想通过onClick访问组件的key
  3. 这是我的console.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>
        );
      })}
    </>
  );
}

来自React docs

Keys serve as a hint to React but they don’t get passed to your components. If you need the same value in your component, pass it explicitly as a prop with a different name:

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

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})或者更好的是 ref. 解释了如何创建多个 refs