React-Leaflet中Popup组件Ref绑定TypeScript报错解决方案咨询
React-Leaflet Popup组件Ref创建问题
我正在使用Leaflet展示地图,需求是在用户点击的位置创建标记,且该标记默认打开Popup弹窗,但在此功能实现时遇到了问题。
代码文件 /src/components/mapcontainer/popup.component.tsx
import { Map, Popup as LeafletPopup } from "leaflet"; import { useRef } from "react"; import { Popup } from "react-leaflet"; import "./popup.style.scss"; type Props = { map: Map; }; const Popmenu = ({ map }: Props) => { const popupRef = useRef<LeafletPopup>(null); popupRef.current && map.openPopup(popupRef.current); return ( <Popup ref={popupRef.current}> <div className="popup"> <button> Set as start</button> <button> Set as destination</button> </div> </Popup> ); }; export default Popmenu;
TypeScript错误
TS2322: Type 'Popup | null' is not assignable to type 'Ref<Popup> | undefined'. Type 'Popup' is not assignable to type 'Ref<Popup> | undefined'. 13 | 14 | return ( > 15 | <Popup ref={popupRef.current}> | ^^^
核心问题
如何正确为React-Leaflet的Popup组件创建Ref?
依赖版本信息(package.json)
{ "name": "bike-router", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^5.16.5", "@testing-library/react": "^13.4.0", "@testing-library/user-event": "^13.5.0", "@types/jest": "^29.2.0", "@types/node": "^18.11.3", "@types/react": "^18.0.21", "@types/react-dom": "^18.0.6", "leaflet": "^1.9.2", "react": "^18.2.0", "react-dom": "^18.2.0", "react-leaflet": "^4.1.0", "react-scripts": "5.0.1", "sass": "^1.55.0", "typescript": "^4.8.4", "web-vitals": "^2.1.4" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "devDependencies": { "@types/leaflet": "^1.9.0" } }
内容的提问来源于stack exchange,提问作者Hasan Aga
相关产品推荐
相关产品推荐

