Using a regular javascript library inside a React component

前端 未结 1 437
攒了一身酷
攒了一身酷 2021-02-13 14:49

I\'m curious what\'s the best way to use a regular javascript library (not written as a React component) inside a React environment.

For example, let\'s say there\'s a j

1条回答
  •  孤城傲影
    2021-02-13 15:30

    The main purpose of JSX is to feel like HTML. The main purpose of render in a React component is to render that "fake" (virtual) HTML. If your external widget is also a React component, the solution is straightforward:

    class MainView extends Component {
      render() {
        return (
          

    Hello look at my cool widget library

    ); } }

    All you have to make sure is that the code above runs after your widget script is loaded (so the Widget component is present). The exact solution to this would depend on your build system.

    If your external library is not a React component, then you cannot use a custom widget tag and you must render actual HTML.

    The big trick is to not return from render but manually render ourselves after the widget initializes what it needs:

    class MainView extends Component {
      render() {
        // don't render anything
        return 
    ; }, componentDidMount() { // find the DOM node for this component const node = ReactDOM.findDOMNode(this); // widget does stuff $(node).activateMyCoolWidget(); // start a new React render tree with widget node ReactDOM.render(
    {this.props.children}
    , node); } });

    Take a look at portals for more details.

    0 讨论(0)
提交回复
热议问题