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