3

I wanted to add some widgets in my Typescript React component. Here is the embed code

export default class App extends React.Component {

  render(): ReactNode {
    return (
      <div>
        Chart test
        <div className="tradingview-widget-container">
          <div className="tradingview-widget-container__widget"></div>

          <script type="text/javascript" src="https://s3.tradingview.com/external-embedding/embed-widget-ticker-tape.js" async>
            {JSON.stringify({
              "symbols": [
                {
                  "proName": "OANDA:SPX500USD",
                  "title": "S&P 500"
                },
                {
                  "proName": "OANDA:NAS100USD",
                  "title": "Nasdaq 100"
                },
                {
                  "proName": "FX_IDC:EURUSD",
                  "title": "EUR/USD"
                },
                {
                  "proName": "BITSTAMP:BTCUSD",
                  "title": "BTC/USD"
                },
                {
                  "proName": "BITSTAMP:ETHUSD",
                  "title": "ETH/USD"
                }
              ],
              "colorTheme": "light",
              "isTransparent": false,
              "displayMode": "adaptive",
              "locale": "in"
            })}
          </script>
        </div>
      </div>
    );
  }
}

Seems like the same is rendered on the browser DOM as well. Unfortunately, the chart never gets loaded:

the chart never gets loaded

Working perfectly in jsFiddle

Note that the JSON data is also passed to the script. This solution doesn't talk about it.

Seems like I'm doing it wrong. What is the right way to inject it?

4

1 回答 1

2

这对我有用!

export default class App extends React.Component {
    componentDidMount(): void {

      if (document.getElementById("chart")) {
        const script = document.createElement('script');
        script.src = 'https://s3.tradingview.com/external-embedding/embed-widget-ticker-tape.js'
        script.async = true;
        script.innerHTML = JSON.stringify({
          "symbols": [{
            "proName": "OANDA:SPX500USD",
            "title": "S&P 500"
          }, {
            "proName": "OANDA:NAS100USD",
            "title": "Nasdaq 100"
          }, {
            "proName": "FX_IDC:EURUSD",
            "title": "EUR/USD"
          }, {
            "proName": "BITSTAMP:BTCUSD",
            "title": "BTC/USD"
          }, {
            "proName": "BITSTAMP:ETHUSD",
            "title": "ETH/USD"
          }],
          "colorTheme": "light",
          "isTransparent": false,
          "displayMode": "adaptive",
          "locale": "in"
        });

        document.getElementById("chart")!.appendChild(script);;
      }

    }


    render(): ReactNode {
      return (<div id="chart"> </div>);
      }
    }
于 2019-11-11T18:19:44.913 回答