点击瓣叶标记react typescript时如何调用setState

wkyowqbh  于 2023-03-31  发布在  TypeScript
关注(0)|答案(1)|浏览(136)

我有一个设备列表,我用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='&copy; <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>
  );
}

我试过很多方法,都不管用

jfewjypa

jfewjypa1#

不应将状态声明为
const [selectedEquipmentId,setSelectedEquipmentId] = useState(“”);
接口为
selectedEquipmentId:弦|React节点;
因为ReactNode不能是字符串。所以如果你不需要ReactNode应该删除它,如果你出于某种原因需要它,需要将它添加到状态类型。
也可以执行ISelectedEquipmentIdContext['selectedEquipmentId'],但对于ID,您很可能只需要字符串类型。

相关问题