“onclick” 属性在 React 应用内的锚元素中

huangapple go评论74阅读模式
英文:

"onclick" attribute in anchor element inside react app

问题

要在React组件中为锚点元素添加一个名为"onclick"的属性,你可以使用dangerouslySetInnerHTML属性。以下是代码示例:

return (
  <div>
    <span>.....</span>
    <a
      href="someurl"
      dangerouslySetInnerHTML={{ __html: 'onclick="javascript:..."' }}
    >
      ...somemore element
    </a>
  </div>
);

通过使用dangerouslySetInnerHTML,你可以将HTML字符串直接注入到元素中,包括特殊属性。但请注意,这是一种潜在的安全风险,因为它可以导致跨站脚本(XSS)攻击,应谨慎使用。确保你的"onclick"属性值是安全的,不包含潜在的恶意内容。

英文:

i want to create a react component which should render a tree of nodes, in which one of the element is supposed to be an anchor. The JSX would be:

return(
  &lt;div&gt;
    &lt;span&gt;.....&lt;/span&gt;
    &lt;a href=&quot;someurl&quot; onclick=&quot;javascript:.....&quot;
    ...somemore element
  &lt;/div&gt;
);

I want to add an aatribute "onclick" to the anchor element. How can i achieve it? I don't want to use onClick method of reactJS, which is equivalent to addEventListner method. I want to define it as attribute to anchor, so that it should appear as below in html dom tree:

&lt;a href=&quot;..&quot; onclick=&quot;javascript:...&quot;

答案1

得分: 1

这不适用于React,因为它不会将常规的 onclick 属性传递。这也没有意义,因为建议使用 onClick 可以执行相同的操作。

英文:

This won't work with React as it will not pass a regular onclick attribute through. It also makes no sense, as the recommended onClick can do all the same things.

&lt;a href=&quot;...&quot; onClick={() =&gt; alert(&#39;hello&#39;)}&gt;Link&lt;/a&gt;

答案2

得分: 1

import React from 'react';

export function App(props) {
  const html = '<a onclick="javascript:alert(2)">bbb</a>';
  return (
    <div className='App'>
      <h1>Hello React.</h1>
      <h2>Start editing to see some magic happen!</h2>
      <div dangerouslySetInnerHTML={{__html: html}}></div>
    </div>
  );
}
英文:
import React from &#39;react&#39;;

export function App(props) {
  const html = &#39;&lt;a onclick=&quot;javascript:alert(2)&quot;&gt;bbb&lt;/a&gt;&#39;;
  return (
    &lt;div className=&#39;App&#39;&gt;
      &lt;h1&gt;Hello React.&lt;/h1&gt;
      &lt;h2&gt;Start editing to see some magic happen!&lt;/h2&gt;
      &lt;div dangerouslySetInnerHTML={{__html: html}}&gt;&lt;/div&gt;
    &lt;/div&gt;
  );
}

I used this code here: https://playcode.io/react and it worked. dangerouslySetInnerHTML allows you to set the html raw, but I think it requires a parent DOM element, like the div above. I don't know if you can do it without a parent element to set the html of.

huangapple
  • 本文由 发表于 2023年3月8日 19:08:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75672225.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定