Using a regular javascript library inside a React component

前端 未结 1 436
攒了一身酷
攒了一身酷 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 (
          <div>
            <h1>Hello look at my cool widget library</h1>
            <Widget width="600" height="400" />
          </div>
        );
      }
    }
    

    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 <div/>;
      },
    
      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(<div>{this.props.children}</div>, node);
      }
    });
    

    Take a look at portals for more details.

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