英文:
"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(
<div>
<span>.....</span>
<a href="someurl" onclick="javascript:....."
...somemore element
</div>
);
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:
<a href=".." onclick="javascript:..."
答案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.
<a href="..." onClick={() => alert('hello')}>Link</a>
答案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 '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>
);
}
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论