简体   繁体   中英

Access React DOM Element from external script

I am trying to get access to a React DOM element 'id' from an external script file. I believe my script is being imported correctly as console.log('test') from the file is working, though console.log(myDiv) returns null.

How can I achieve this in React?

// COMPONENT

import './../data/script.ts';

  render() {
    return (
        <div id='targetDiv'>
          <p>{This will be populated from my external script file...}</p>
        </div>
    );
  }

// SCRIPT

  var myDiv = document.getElementById('targetDiv');
  console.log(myDiv);

To fix the issue I needed to import my external script as a function, and then call the function after the component mounted:

// COMPONENT

import { myScript } from './../data/script';

  componentDidMount() {
    {
      myScript();
    }
  }

  render() {
    return (
        <div id='targetDiv'>
          {My script now renders correctly inside the div}
        </div>
    );
  }

// SCRIPT

  var myDiv = document.getElementById('targetDiv');
  const d = document.createElement('p');
  myDiv.appendChild(d);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM