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

reactjs - Cannot read property 'addEventListener' of null using javascript in react?

I am trying to use native javascript in react to bind event .Actually I am getting some HTML from server .I am using dangerouslySetInnerHTML to set HTML .Now I want to bind a click event in incoming HTML from server here is my code https://codesandbox.io/s/angry-shadow-1c4v8?file=/src/App.js

 useEffect(() => {
    const alertFunc = function () {
      alert("-----");
    };
    document.querySelector(".btn").addEventListener("click", alertFunc, false);
    // Specify how to clean up after this effect:
    return function cleanup() {
      document
        .querySelector(".btn")
        .removeEventListener("click", alertFunc, false);
    };
  });
question from:https://stackoverflow.com/questions/65624096/cannot-read-property-addeventlistener-of-null-using-javascript-in-react

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

1 Reply

0 votes
by (71.8m points)

This issue is because of your template - <button className="btn">set countor </button> is redering like below.

enter image description here

So that if you try to access using class query selector, it will return undefined. You can use class instead of className.

 return {
    __html: '<button class="btn">set countor </button>'
  };

Working Code - https://codesandbox.io/s/brave-meadow-qitjb?file=/src/App.js:87-157


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

...