如何在 React 组件中使用 TradingView 小部件?
Posted
技术标签:
【中文标题】如何在 React 组件中使用 TradingView 小部件?【英文标题】:How to use TradingView widgets in a React component? 【发布时间】:2022-01-20 00:29:22 【问题描述】:此小部件与 SO 上的其他示例略有不同。其他示例只有一个带有 url src 的脚本标签,但这个小部件有另一个带有函数的脚本标签。
这是我从他们的网站上复制的。 Tradingview widgets
<!-- TradingView Widget BEGIN -->
<div class="tradingview-widget-container">
<div id="tradingview_ca190"></div>
<div class="tradingview-widget-copyright"><a href="https://www.tradingview.com/symbols/NASDAQ-AAPL/" rel="noopener" target="_blank"><span class="blue-text">AAPL Chart</span></a> by TradingView</div>
<script type="text/javascript" src="https://s3.tradingview.com/tv.js"></script>
<script type="text/javascript">
new TradingView.widget(
"width": 980,
"height": 610,
"symbol": "NASDAQ:AAPL",
"interval": "D",
"timezone": "Etc/UTC",
"theme": "dark",
"style": "1",
"locale": "en",
"toolbar_bg": "#f1f3f6",
"enable_publishing": false,
"allow_symbol_change": true,
"container_id": "tradingview_ca190"
);
</script>
</div>
<!-- TradingView Widget END -->
【问题讨论】:
类似问题:***.com/questions/53845011/… 【参考方案1】:此解决方案有效,但每次符号更改时都会重新渲染小部件。如果您更改小部件本身的符号,则只会呈现价格图表和交易量图表。
import React, useState, useEffect from "react";
import Helmet from 'react-helmet';
const DrawChart = ( symbol='AAPL' ) =>
const useScript = url =>
useEffect(() =>
const script = document.createElement('script');
script.src = url;
script.async = true;
document.body.appendChild(script);
return () =>
document.body.removeChild(script);
, [url]);
;
return (
<div className="tradingview-widget-container">
useScript('https://s3.tradingview.com/tv.js')
<div id="tradingview_2d7e4"></div>
<div className="tradingview-widget-copyright">
<a href="https://www.tradingview.com/symbols/NASDAQ-AAPL/" rel="noopener" target="_blank"></a>
</div>
<Helmet>
<script type="text/javascript">`
new window.TradingView.widget(
"width": 400,
"height": 400,
"symbol": \`$symbol\`,
"interval": "D",
"timezone": "Etc/UTC",
"theme": "dark",
"style": "1",
"locale": "en",
"toolbar_bg": "#f1f3f6",
"enable_publishing": false,
"allow_symbol_change": true,
"container_id": "tradingview_2d7e4"
)
`
</script>
</Helmet>
</div>
)
export default DrawChart;
【讨论】:
以上是关于如何在 React 组件中使用 TradingView 小部件?的主要内容,如果未能解决你的问题,请参考以下文章
如何在 React 经典 `class` 组件中使用 React 钩子?
如何在另一个 React 组件中正确使用 TabNavigator