简体   繁体   English

危险地反应SetInnerHTML onClick 不起作用

[英]React dangerouslySetInnerHTML onClick not working

Hi I am very new to react just trying to add onClick inside the html render by the dangerouslySetInnerHTML嗨,我很新,只是试图通过危险的SetInnerHTML 在html 渲染中添加onClick

Here is the code example这是代码示例

import "./styles.css";
import React from "react";

export default function App() {
  const hello = (event) => {
    alert("hello", event.target);
  };
  const displayUrl = () => {
    const str = `<a onClick=${hello} href="#">Test</a>`;
    return <div dangerouslySetInnerHTML={{ __html: str }} />;
    //return `<a href='#'>Test</a>`;
  };

  return (
    <div className="App">
      <React.Fragment>{displayUrl()}</React.Fragment>
    </div>
  );
}

Codesandbox example 代码沙盒示例

Please help me to understand why it's not working请帮助我理解为什么它不起作用

As pointed out in the comments (and as indicated by the property name), you should avoid using dangerouslySetInnerHTML as much as possible (I would say don't use it at all until you understand React very well).正如评论中所指出的(以及属性名称所指示的),您应该尽可能避免使用dangerouslySetInnerHTML SetInnerHTML(我会说在您非常了解 React 之前不要使用它)。 Here there is a straightforward React approach to setting the onClick function on an element.这里有一个简单的 React 方法来设置元素上的onClick函数。

You need to render the element with the onClick normally and just pass onClick as a prop.您需要正常使用onClick渲染元素,并将onClick作为道具传递。

For example:例如:

import React from "react";
import "./styles.css";

export default function App() {
  const hello = (event) => {
    alert("hello", event.target);
  };

  return (
    <div className="App">
      <button onClick={hello}>Click here</button>
    </div>
  );
}

With a link (as your sandbox has and question suggests), you can use the a element and set the href to the desired URL.使用链接(正如您的沙箱和问题所建议的那样),您可以使用a元素并将href设置为所需的 URL。

For example:例如:

import React from "react";
import "./styles.css";

export default function App() {
  const url = "http://example.com"

  return (
    <div className="App">
      <a href={url}>Click here</a>
    </div>
  );
}

And url can come from anywhere you'd like (eg props or fetched from somewhere and held in state).并且url可以来自您想要的任何地方(例如道具或从某处获取并保持状态)。

You're setting an onClick listener, which is React in HTML.您正在设置一个onClick侦听器,它是 HTML 中的 React。 To run javascript after a click event, you're better off using the <button> element.要在单击事件后运行 javascript,最好使用<button>元素。

Try something like this:尝试这样的事情:

const displayUrl = () => {
  const str = ` <button onclick="${hello}">Click me</button> `
  return <div dangerouslySetInnerHTML={{ __html: str }} />
};

Please keep in mind that using dangerouslySetInnerHTML isn't best practice.请记住,使用dangerouslySetInnerHTML不是最佳实践。 I would follow Henry Woody's answer.我会遵循亨利伍迪的回答。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM