Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

reactjs - onClick attached to hyperlink does not run

When I click the <a href onClick>Fire</a> or <a href onClick>Storm</a>, the console should receive !!!!!!!!!!!!! from toggle(), but it does not. Any idea why that is?

const Map = ({ eventData, center, zoom }) => {
    //location box after click
    const [locationInfo, setLocationInfo] = useState(null);
    const [infoBox, setInfoBox] = useState(true);
    const [idx, setIdx] = useState(eventData);

    
    const toggle = (index) => {
        console.log('!!!!!!!!!!!!!');
        setIdx(idx.filter((ev) => ev.categories[0].id === index));
    }
    

    return (
        <div>
            <div id="mySidenav" className="sidenav">
                <a href="" id="Fire" onClick = {() => toggle(10)}>Fire</a>
                <a href="" id="Storm" onClick = {() => toggle(8)}>Storm</a>
            </div> 
 
            <Header/>
            {/*reload this component*/}
            <div className="map">
                <GoogleMapReact
                    bootstrapURLKeys={{ key: process.env.REACT_APP_API_KEY }}
                    defaultCenter={ center }
                    defaultZoom={ zoom }
                >
            {idx.map((ev, index) => {
                if(ev.categories[0].id === 8 || ev.categories[0].id === 10) {
                    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);
                    }} />
                }
            })}
                </GoogleMapReact>
 
                {infoBox && 
                    <div  onClick={()=> setInfoBox(!infoBox)}>
                        {locationInfo && <LocationInfoBox info={locationInfo}/>}
                    </div>
                }
            </div>
        </div>
    )
}
question from:https://stackoverflow.com/questions/65864492/onclick-attached-to-hyperlink-does-not-run

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is not required to add the href attribute. The onClick event will be fired:

<a onClick={()=> console.log("click")}>Fire</a>

If you won't use it then you don't need to put it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...