简体   繁体   English

如何将onClick功能传递到使用字符串文字创建的范围?

[英]How to pass onClick funtion into a span created using string literals?

I have an HTML object created using string literals and used Dangerously Set HTML. 我有一个使用字符串文字创建的HTML对象,并使用了Dangerously Set HTML。 Basically, I just had to create span and pass onClick while creating the string literal but when I pass the function which is bound in the constructor. 基本上,我只需创建span并在创建字符串文字时传递onClick,但是当我传递绑定在构造函数中的函数时。 later I get the error that this is not a function. 后来我得到的错误是这不是一个功能。 How can I pass a function in onClick while creating the HTML object using string literals in react? 如何在反应中使用字符串文字创建HTML对象时在onClick中传递函数? this HTML is set dangerously in render(). 这个HTML在render()中设置得很危险。

var html=`<span onClick="myFunc()">${text}</span>`;

this just a string, you can't have eventListerner on it. 这只是一个字符串,你不能有eventListerner。

Or declare a DOM element like this 或者声明像这样的DOM元素

var MySpan = Document​.create​Element('span');
MySpan.textContent = text;
MySpan.onclick = myFunc;


//....

function myFunc() {
  alert('span clicked !');
}

you can do like this: var html = {text}. 你可以这样做:var html = {text}。 Now the 'html' can be sue as pure component in he mail component to render in DOM but here this.myFunc is wrong because pure component will not carry any scope by itself , ou have to pass the function as prop or use HOC for that. 现在'html'可以起作为邮件组件中的纯组件来在DOM中呈现但是这里this.myFunc是错误的,因为纯组件本身不会携带任何范围,你必须将函数作为prop传递或使用HOC来实现。

And for more clearity kindly gothrough this pure component documentation of react : react pure component 为了更清楚,请通过这个纯组件记录反应: 反应纯组分

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

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