[英]How to call a function in react js from an external JS File
I was trying to create a pop over for one of my elements which are using react and bootstrap. 我正在尝试为使用React和Bootstrap的元素之一创建弹出窗口。
Following is my React Code:- 以下是我的React代码:-
class Share extends React.Component{
render(){
return(
<div>hello</div>
);
}
}
var shareRenderFunc=function() {
ReactDOM.render(
<Share/> , document.getElementById('shareContainer')
);
}
Following is my jquery called the shareRenderFunc() :- 以下是我的名为shareRenderFunc()的 jquery:
var popOverSettings = {
placement: 'bottom',
container: 'body',
selector: '[rel="popover"]',
content: function(){
window.shareRenderFunc();
return $('#shareContainer').html();
}
}
$('body').popover(popOverSettings);
Following is my HTML containing the popover element:- 以下是我的HTML包含popover元素:-
<div className="like-share icons-gray-black">
<a href=""><span><i className="fa fa-heart" aria-hidden="true"></i></span></a>
<a><span><i className="share-social fa fa-share-alt" rel="popover" aria-hidden="true"></i></span></a>
</div>
But in the console I am getting TypeError saying shareRenderFunc is not a function 但是在控制台中,我收到TypeError提示shareRenderFunc不是函数
PS: the reactjs file is loaded before the jquery file so the function called is already there, i tried same by creating another javascript file and calling function present in there and it seems to be working fine. PS:reactjs文件是在jquery文件之前加载的,因此调用的功能已经存在,我尝试通过创建另一个javascript文件并调用其中存在的功能来尝试相同的功能,并且看起来工作正常。
Your shareRenderFunc
only exists in the local scope of your Share
class. 您的
shareRenderFunc
仅存在于Share
类的本地范围内。 You need to define it as global via the window
object : 您需要通过
window
对象将其定义为global:
class Share extends React.Component{
render(){
return(
<div>hello</div>
);
}
}
window.shareRenderFunc=function() {
ReactDOM.render(
<Share/> , document.getElementById('shareContainer')
)
);
did u try to change 你有没有尝试改变
var shareRenderFunc=function() {
ReactDOM.render(
<Share/> , document.getElementById('shareContainer')
);
}
in to this... 对此...
function shareRenderFunc(){
ReactDOM.render(
<Share/> , document.getElementById('shareContainer')
);
}
you only need to call the function wihtout params if you didnt' set one. 如果您未设置参数,则只需要调用wihtout参数函数即可。
shareRenderFunc();
PS: If you want your jQuery load before your reactsjs, then try to write your jQuery script over your reactsjs line PS:如果您希望在reactsjs之前加载jQuery,请尝试在reactsjs行上编写jQuery脚本
<script src="jquery ...."></script>
/* and here your reactsjs */
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.