[英]Component not rendering with onClick event React
So I'm using google-map-react and trying to get a popup to show when I click on an icon that I have plotted on the map.因此,我正在使用 google-map-react 并尝试在单击我在 map 上绘制的图标时显示一个弹出窗口。 Right now, if you click the icon, the console logs it correctly but nothing is showing up.
现在,如果您单击该图标,控制台会正确记录它,但没有显示任何内容。 Here's a snippet of code
这是一段代码
const ToolTip = ({name, address, info}) => <div>
<h1>{name}</h1>
<h2>{address}</h2>
<p>{info}</p>
</div>;
var showToolTip = (name) => {
currentToolTip = name
console.log(currentToolTip === name)
}
var currentToolTip = ""
const directory = places.map((data) => {
//category - Directory
if ((data.category === ButtonTitle.CampusSeeking) && data.deptMarker === "")
return (
<div lat={data.latitude}
lng={data.longitude}>
<Pin
lat={data.latitude}
lng={data.longitude}
color={blue}
height="25px"
width="25px"
onClick = {() => showToolTip(data.name)}
/>
{currentToolTip === data.name &&
<ToolTip
lat={data.latitude}
lng={data.longitude}
name = {data.name}
address = {data.address}
info = {data.info}>
</ToolTip>}
</div>
);
......
return (
{loc === ButtonTitle.CampusSeeking && directory} )
You may need to change currentToolTip
to be a state instead of a local variable var currentToolTip = ""
to trigger render if name changed您可能需要将
currentToolTip
更改为 state 而不是局部变量var currentToolTip = ""
以在名称更改时触发渲染
const [currentToolTip, setCurrentToolTip] = useState("")
var showToolTip = (name) => {
setCurrentToolTip(name)
}
You need to use state:您需要使用 state:
// replace
var currentToolTip = ""
// with
const [currentTooltip,setCurrentTooltip] = React.useState("");
and和
var showToolTip = (name) => {
setCurrentTooltip(name)
}
Keep currentTooltip as a state instead of a normal variable.将 currentTooltip 保留为 state 而不是普通变量。
const [currentToolTip, setCurrentToolTip] = useState(null);
And then change this onClick on the icon.然后在图标上更改这个onClick。
<Pin
...
...
...
onClick = {() => setCurrentToolTip(data.name)}
>
Because states and props can cause re-render but the normal variable can't.因为状态和道具会导致重新渲染,但普通变量不能。 That's why your
currentToolTip === data.name
this logic is getting false every time.这就是为什么您的
currentToolTip === data.name
这个逻辑每次都变得错误的原因。 Hence the tooltip is not rendering.因此,工具提示未呈现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.