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
198 views
in Technique[技术] by (71.8m points)

reactjs - how to add click event listener in javascript in react js?

can you please help how to add click event listener in react-project without using react - onClick attribute. I want to use only native javascript.

I tried like this

document.addEventListener("DOMContentLoaded", function (event) {
  console.log("====");
  console.log(document.querySelector(".btn"));
  document.querySelector(".btn").addEventListener(
    "click",
    function () {
      alert("-----");
    },
    false
  );
});

it is not working alert is not showing .can you please help me where i doing wrong.

https://codesandbox.io/s/angry-shadow-1c4v8?file=/src/App.js:76-340

I know using react we can acheive this but I don't want to use reactjs click event I want to use native javascript and update the state.

below solution not working when I am using dangerouslyInsertHTML

here is my code https://codesandbox.io/s/angry-shadow-1c4v8?file=/src/App.js

question from:https://stackoverflow.com/questions/65623013/how-to-add-click-event-listener-in-javascript-in-react-js

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

1 Reply

0 votes
by (71.8m points)

you must register event listener in React Hooks

try this

import React, { useEffect, useState, useRef } from "react";

export default function App() {
  const [counter, setCounter] = useState(0);
  const buttonEl = useRef(null);
  useEffect(() => {
    console.log(counter);
  }, [counter]);

  useEffect(() => {
    const alertFunc = function () {
      alert("-----");
    }
    const buttonRef = buttonEl.current;
    buttonRef.addEventListener(
      "click",
      alertFunc,
      false
    ); 
    // Specify how to clean up after this effect:
    return function cleanup() {
      buttonRef.removeEventListener("click", alertFunc, false)
    };
  })
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <button className="btn" ref={buttonEl}> set countor</button>
    </div>
  );
}

I register listener in hooks, and when the component will unmount I remove the listener


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

...