我有一个设备列表,我用Array.map
显示它们,我有一个状态为[selectedEquipmentId, setSelectedEquipmentId]
的Context API。
我希望当我点击<Marker/>
时调用setSelectedEquipmentId(equipmentId)
。
这是一个简单的onClick
,但源代码的方式不与传单,我不能找到这个答案。
function Map() {
const equipmentsPositions = useContext(EquipmentsPositionContext);
const setSelectedEquipmentId = useContext(EquipmentIdContext);
const center: LatLngExpression = [-19.151801, -46.007759];
function getEquipmentById(equipmentId: string) {
const filteredEquipment = equipmentsStateHistory.filter(
(equipment) => equipment.equipmentId === equipmentId
);
return filteredEquipment[0];
}
return (
<Box h="100vh" w="80%">
<MapContainer
center={center}
zoom={10}
scrollWheelZoom={true}
style={{ height: "100%", width: "100%" }}
>
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{equipmentsPositions?.map((equipmentPosition) => {
const equipment = getEquipmentById(equipmentPosition.equipmentId);
return (
<Marker
onClick={() => {setSelectedEquipmentId(equipment.equipmentId)}}
key={equipment.equipmentId}
position={[
equipmentPosition.positions[equipmentsPositions.length - 1].lat,
equipmentPosition.positions[equipmentsPositions.length - 1].lon,
]}
>
<Popup>
<Text as="span" color={equipment.color}>
{equipment.name}
</Text>
</Popup>
</Marker>
);
})}
</MapContainer>
</Box>
);
}
export default Map;
这里是Context
只是为了上下文哈哈
interface ISelectedEquipmentIdContext {
selectedEquipmentId: string | ReactNode;
setSelectedEquipmentId: React.Dispatch<React.SetStateAction<string>>
}
export const EquipmentIdContext = createContext<ISelectedEquipmentIdContext | null>(
null
);
export function EquipmentIdProvider({ children }: IProps) {
const [selectedEquipmentId, setSelectedEquipmentId] = useState<string>("");
return (
<EquipmentIdContext.Provider value={{ selectedEquipmentId: selectedEquipmentId, setSelectedEquipmentId: setSelectedEquipmentId }}>
{children}
</EquipmentIdContext.Provider>
);
}
我试过很多方法,都不管用
1条答案
按热度按时间jfewjypa1#
不应将状态声明为
const [selectedEquipmentId,setSelectedEquipmentId] = useState(“”);
接口为
selectedEquipmentId:弦|React节点;
因为ReactNode不能是字符串。所以如果你不需要ReactNode应该删除它,如果你出于某种原因需要它,需要将它添加到状态类型。
也可以执行
ISelectedEquipmentIdContext['selectedEquipmentId']
,但对于ID,您很可能只需要字符串类型。