Jer*_*zog 22 html javascript node.js ecmascript-6 reactjs
我想在React中导入这个javascript包
<script src="https://cdn.dwolla.com/1/dwolla.js"></script>
Run Code Online (Sandbox Code Playgroud)
但是,没有NPM包,所以我不能这样导入它:
import dwolla from 'dwolla'
Run Code Online (Sandbox Code Playgroud)
要么
import dwolla from 'https://cdn.dwolla.com/1/dwolla.js'
Run Code Online (Sandbox Code Playgroud)
所以,当我尝试
dwolla.configure(...)
Run Code Online (Sandbox Code Playgroud)
我得到一个错误,说dwolla是未定义的.我该如何解决这个问题?
谢谢
Jer*_*zog 39
转到index.html文件并导入脚本
<script src="https://cdn.dwolla.com/1/dwolla.js"></script>
Run Code Online (Sandbox Code Playgroud)
然后,在导入dwolla的文件中,将其设置为变量
const dwolla = window.dwolla;
Run Code Online (Sandbox Code Playgroud)
对于打字稿开发人员
const newWindowObject = window as any;
// 将其转换为任何类型
let pushNotification = newWindowObject.OneSignal;
// 现在 OneSignal 对象可以在打字稿中访问而不会出现错误
这个问题越来越老了,但我找到了一种使用react-helmet
库来解决这个问题的好方法,我觉得它更符合 React 的工作方式。我今天用它来解决一个类似于你的 Dwolla 问题的问题:
import React from "react";
import Helmet from "react-helmet";
export class ExampleComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
myExternalLib: null
};
this.handleScriptInject = this.handleScriptInject.bind(this);
}
handleScriptInject({ scriptTags }) {
if (scriptTags) {
const scriptTag = scriptTags[0];
scriptTag.onload = () => {
// I don't really like referencing window.
console.log(`myExternalLib loaded!`, window.myExternalLib);
this.setState({
myExternalLib: window.myExternalLib
});
};
}
}
render() {
return (<div>
{/* Load the myExternalLib.js library. */}
<Helmet
script={[{ src: "https://someexternaldomain.com/myExternalLib.js" }]}
// Helmet doesn't support `onload` in script objects so we have to hack in our own
onChangeClientState={(newState, addedTags) => this.handleScriptInject(addedTags)}
/>
<div>
{this.state.myExternalLib !== null
? "We can display any UI/whatever depending on myExternalLib without worrying about null references and race conditions."
: "myExternalLib is loading..."}
</div>
</div>);
}
}
Run Code Online (Sandbox Code Playgroud)
使用this.state
意味着 React 将自动监视 myExternalLib 的值并适当地更新 DOM。
信用:https : //github.com/nfl/react-helmet/issues/146#issuecomment-271552211
归档时间: |
|
查看次数: |
30515 次 |
最近记录: |