如何调用使用react外部定义的javascript函数?
我正在使用如何调用使用react外部定义的javascript函数?,javascript,reactjs,Javascript,Reactjs,我正在使用react.js在html页面上呈现。在这个脚本中,我需要从react类中调用一个javascript函数 这就是我所拥有的 class Example extends React.Component { componentWillMount() { //render a script const script = document.createElement("script"); script.src = "http//
react.js
在html页面上呈现
。在这个脚本中,我需要从react类中调用一个javascript函数
这就是我所拥有的
class Example extends React.Component {
componentWillMount() {
//render a script
const script = document.createElement("script");
script.src = "http//random_source.js";
render(){
//call method from the script rendered
window.someMethod();
return(
<div>{this.componentWillMount}</div>
);
}
}
类示例扩展了React.Component{
componentWillMount(){
//渲染脚本
常量脚本=document.createElement(“脚本”);
script.src=“http//random_source.js”;
render(){
//从呈现的脚本调用方法
window.someMethod();
返回(
{this.componentWillMount}
);
}
}
因此,componentWillMount()
正在html页面上呈现我的脚本,并且在render()
中我正在调用窗口。someMethod()
其中someMethod
位于呈现的脚本内部
使用react可以吗?如果没有,有什么解决办法吗?是的,使用react JS确实可以。我已经使用它实现了一些滚动事件。唯一的条件是,您的javascript应该在react JS组件加载之前加载,否则将抛出未定义的错误
但是,如果仅此特定组件需要此操作,则只能实现组件类。脚本是异步的,因此需要等待加载和解析脚本。完成此操作后,将触发
onload
回调/事件
class Example extends React.Component {
getInitialState(){
return {loaded:false} //initially not loaded
}
componentWillMount() {
//render a script
const script = document.createElement("script");
script.src = "http//random_source.js";
//when the script loads, we're ready to go, so change state
script.onload = (function(){
this.setState({loaded: true})
}).bind(this);
//append the script to the DOM
//you should take care not to include it twice
// and if include to setState to loaded just as script.onload does
document.getElementsByTagName('head')[0].appendChild(script);
}
render(){
if(!this.state.loaded){
return (<div>Loading...</div>);
}
//call method from the script rendered
window.someMethod();
return(
<div>{this.componentWillMount}</div>
);
}
}
类示例扩展了React.Component{
getInitialState(){
返回{loaded:false}//初始未加载
}
componentWillMount(){
//渲染脚本
常量脚本=document.createElement(“脚本”);
script.src=“http//random_source.js”;
//当脚本加载时,我们就可以开始了,所以请更改状态
script.onload=(函数(){
this.setState({loaded:true})
}).约束(本);
//将脚本附加到DOM
//你应该注意不要把它包括两次
//如果包含,则将状态设置为加载,就像script.onload一样
document.getElementsByTagName('head')[0].appendChild(脚本);
}
render(){
如果(!this.state.loaded){
返回(加载…);
}
//从呈现的脚本调用方法
window.someMethod();
返回(
{this.componentWillMount}
);
}
}
听起来你在问这是否有效。为什么不试试呢?@CalebAnthony我确实试过了看看我的代码^^@Bolboa可能是这样的-,但是,为什么你需要在react组件中加载脚本?你使用webpack吗?也许最好将此脚本添加到general bundle中?@Alexander。我没有访问该webpack的权限,这就是我想要它的原因这样做,但您的答案解决了我上面的例子中的问题,javascript是在调用方法之前还是之后加载的?为什么要这样实现?我的意思是从reactjs创建js元素?为什么不将js文件放在html中,用webpack编译reactjs文件,并将捆绑文件放在html代码的下面?