gpt4 book ai didi

javascript - 将 javascript 标签加载到 React 组件中

转载 作者:行者123 更新时间:2023-12-03 05:32:05 24 4
gpt4 key购买 nike

我正在尝试加载 Trading View Widget在 react 组件内。我尝试使用 _dangerouslySetInnerHTML,但是,它不运行 javascript 代码。

我也尝试过这个:

import React from 'react';

export default class TradingView extends React.Component{

constructor(props){
super(props);
}

componentDidMount() {
const tradingViewCode = '<!-- TradingView Widget BEGIN --><script type="text/javascript" src="https://d33t3vvu2t2yu5.cloudfront.net/tv.js"></script><script type="text/javascript">new TradingView.widget({"autosize": true,"symbol": "BITFINEX:BTCUSD","interval": "D","timezone": "America/New_York","theme": "White","style": "1","locale": "en","toolbar_bg": "#f1f3f6","enable_publishing": false,"hide_top_toolbar": true,"save_image": false,"hideideas": true});</script><!-- TradingView Widget END -->';
new Function(tradingViewCode)();
}

render(){
return (
<noscript />
);
}
}

最佳答案

一种方法可能是创建这些脚本元素并将其附加到您的 <head>在 componentDidMount 中像这样:

componentDidMount() {
var headElem = document.getElementsByTagName('head')[0];

var tradingWidgetSource = document.createElement('script');
tradingWidgetSource.type = "text/javascript";
headElem.appendChild(tradingWidgetSource);
tradingWidgetSource.onload = function(){
// Do your init logic here instead of the <script> tag.
new TradingView.widget({"autosize": true,"symbol": "BITFINEX:BTCUSD","interval": "D","timezone": "America/New_York","theme": "White","style": "1","locale": "en","toolbar_bg": "#f1f3f6","enable_publishing": false,"hide_top_toolbar": true,"save_image": false,"hideideas": true});
}
tradingWidgetSource.src = "https://d33t3vvu2t2yu5.cloudfront.net/tv.js";
}

关于javascript - 将 javascript 标签加载到 React 组件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40899497/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com