reactjs - 使用状态钩子触发一系列事件
问题描述
当点击不同的按钮时,这部分假设在地图上显示不同的标记。我想添加一个钩子来触发这些重新渲染。动作发生在<a>
and{alertIcon}
中。当我单击 时,我想alertIcon
更改为不同的标记集<a>
,它具有onClick
使用该setAlertIcon
功能的
const Map = ({ eventData, center, zoom }) => {
const [locationInfo, setLocationInfo] = useState(null);
const [infoBox, setInfoBox] = useState(true);
const [alertIcon, setAlertIcon] = useState();
function marker(idx) {return eventData.map((ev, index) => {
if(ev.categories[0].id === idx) {
console.log(idx);
return <LocationMarker key = {index} lat={ev.geometries[0].coordinates[1]} lng={ev.geometries[0].coordinates[0]} onClick={() => {
setLocationInfo({ id: ev.id, title: ev.title });
setInfoBox(!infoBox);
}} />
}
return null
})}
return (
<div>
<div id="mySidenav" className="sidenav">
//click here and trigger event, pass parameter to function
<a href="#" id="Fire" onClick = {() => {
setAlertIcon(()=>marker(10));
}}>Fire</a>
<a href="#" id="Storm">Storm</a>
</div>
<Header/>
{/*reload this component*/}
<div className="map">
<GoogleMapReact
bootstrapURLKeys={{ key: process.env.REACT_APP_API_KEY }}
defaultCenter={ center }
defaultZoom={ zoom }
>
{alertIcon} //here is the proble
// supposed to make markers rerender upon onClick events
</GoogleMapReact>
{infoBox &&
<div onClick={()=> setInfoBox(!infoBox)}>
{locationInfo && <LocationInfoBox info={locationInfo}/>}
</div>
}
</div>
</div>
)
}
解决方案
您可以将 idx 更改为 state 并将 alertIcon 替换为 marker()
像这样
const Map = ({ eventData, center, zoom }) => {
const [locationInfo, setLocationInfo] = useState(null);
const [infoBox, setInfoBox] = useState(true);
const [idx, setIdx] = useState();
function marker() {
return eventData.map((ev, index) => {
if(ev.categories[0].id === idx) {
console.log(idx);
return <LocationMarker key = {index} lat={ev.geometries[0].coordinates[1]} lng={ev.geometries[0].coordinates[0]} onClick={() => {
setLocationInfo({ id: ev.id, title: ev.title });
setInfoBox(!infoBox);
}} />
}
return null
})}
return (
<div>
<div id="mySidenav" className="sidenav">
//click here and trigger event, pass parameter to function
<a href="#" id="Fire" onClick = {() => setIdx(10)}>Fire</a>
<a href="#" id="Storm">Storm</a>
</div>
<Header/>
{/*reload this component*/}
<div className="map">
<GoogleMapReact
bootstrapURLKeys={{ key: process.env.REACT_APP_API_KEY }}
defaultCenter={ center }
defaultZoom={ zoom }
>
{marker()}
</GoogleMapReact>
{infoBox &&
<div onClick={()=> setInfoBox(!infoBox)}>
{locationInfo && <LocationInfoBox info={locationInfo}/>}
</div>
}
</div>
</div>
)
}
推荐阅读
- mini-css-extract-plugin - 如何让 mini-css-extract-plugin 与 webpack 5 一起工作?
- css - svg 路径在旋转时从其正常位置移动
- fortran - 为什么 OpenACC 帮派级循环不起作用
- angular - 如何在 TypeScript 中引用 FormControl?
- python - 我正在构建一个人脸检测器,但我在调整捕获帧的大小以匹配模型的大小时遇到了挑战,因此出现以下错误
- python - TFGPT2LMHeadModel 未知位置
- python - 如何列出所有 pytest 设备
- java - 无法使用 Talend 上传到 Snowflake 阶段,NoSuchMethodError
- c# - 鼠标单击“OnTriggerStay”以添加分数,添加超过设定的数量
- python-3.x - 在双 with 语句中使用 psycopg2 执行多个 SQL 查询