简体   繁体   中英

How do you embed and call an external javascript function in a react component?

I'm trying to incorporate this map into an existing grails/react project.

Updated code:

index.js

ReactDOM.render((

    <Router history = {browserHistory}>
        <Route path="/" component={CreateAccount}/>
        <Route path="/menu" component={Menus}/>
        <Route path="/discover" component={DiscoverApp}/>

        <Route path="/NorthAmerica" component={northAmerica}/>
        <Route path="/SouthAmerica" component={southAmerica}/>
        <Route path="/Europe" component={europe}/>
        <Route path="/Asia" component={asia}/>
        <Route path="/Africa" component={africa}/>
        <Route path="/Australia" component={australia}/>
    </Router>

), document.getElementById('root'));

index.gsp

<head>
        <title>Food App</title>
    <link rel="stylesheet" href="${resource(dir: 'css', file: 'text.css')}" type = "text/css">
    <link rel="stylesheet" href="${resource(dir: 'css', file: 'jquery-jvectormap-2.0.3.css')}" type = "text/css" media="screen">
<javascript src="/js/jquery-3.1.1.js" />
<javascript src="jquery-jvectormap-2.0.3.min.js" />
<javascript src="jquery-jvectormap-world-mill-en.mins.js" />
</head>
<body>
<div id="root" align="left"></div>
<br/>
<asset:javascript src="bundle.js"/>
</body>
</html>

and

import React, { Component } from 'react';
import {Link} from 'react-router';
import $ from 'jquery';
import ReactDOM from 'react-dom';

class NorthAmerica extends Component {

    componentDidMount() {
        const el = ReactDOM.findDOMNode(this.display);
        $(el).vectorMap({map: 'world_mill_en'});
    }

    render(){
        return(
            <div>
                <h1>NORTH AMERICA MAP PLACE-HOLDER</h1>
                <li><Link to="/discover">DISCOVER</Link></li>
                <div
                    ref={display => this.display = display}
                />
            </div>
        )
    }
}

export class northAmerica extends React.Component{
    render(){
        return(<NorthAmerica/>);
    }
}

Any suggestions? Thanks!

Updated:

Page loads now... but where the map should be is just a blank div. I get this error in the console:

Uncaught TypeError: (0 , _jquery2.default)(...).vectorMap is not a function
    at NorthAmerica.componentDidMount (bundle.js?compile=false:12781)
    at bundle.js?compile=false:26803
    at measureLifeCyclePerf (bundle.js?compile=false:26613)
    at bundle.js?compile=false:26802
    at CallbackQueue.notifyAll (bundle.js?compile=false:9088)
    at ReactReconcileTransaction.close (bundle.js?compile=false:31708)
    at ReactReconcileTransaction.closeAll (bundle.js?compile=false:5241)
    at ReactReconcileTransaction.perform (bundle.js?compile=false:5188)
    at ReactUpdatesFlushTransaction.perform (bundle.js?compile=false:5175)
    at ReactUpdatesFlushTransaction.perform (bundle.js?compile=false:1438)

refs in React is required to grab the underlying DOM inside the React component. Once that is available in the component, third party library functions like vectorMap can be called on the jQuery element. Here is an example of the React component assuming all appropriate dependent libraries are available to render DOM.

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';

class NorthAmerica extends Component {
  componentDidMount() {
    const el = ReactDOM.findDOMNode(this.display);
    $(el).vectorMap({map: 'world_mill_en'});
  }

  render() {
    return <div>
      <h1>World Map</h1>
      <div 
        ref={display => this.display = display} 
        style={{width: '600px', height: '400px'}} 
      />
    </div>;
  }
}

/*
 * Render the above component into the div#app
 */
ReactDOM.render(<NorthAmerica />, document.getElementById('app'));

Here is the example codepen which does not work because I wasn't able to provide an appropriate version of jqueryvectormap library.

An exported and modified version of the above codepen works. git clone then open index.html in browser.

You should use one of React's component lifecycle methods to execute your function rather than trying to render an inline script tag. Try removing the inline script from the render method and adding a componentDidMount method:

componentDidMount() {
  $(your jQuery function here);
}

Assuming you're using webpack, you'll probably want to declare jquery as an external, but the above should at least get things up and running.

Instead of:

let NorthAmerica = React.createClass({

You can export this straight away:

export default class NorthAmerica extends React.Component {

and then delete your last code block:

export class northAmerica extends React.Component{
    render(){
        return(<NorthAmerica/>);
    }
}

The reason you can't see anything is because your NorthAmerica component is not added to the DOM yet. Try:

ReactDOM.render(
  <NorthAmerica />,
  document.getElementById('root')
);

Where 'root' is replaced with the name of a div in your index.gsp which is the container for all react content, refer to enter link description here

For this to work you will need an extra import:

import ReactDOM from 'react-dom';

Export is only required if you are using NorthAmerica from another file. If you are not doing that yet then it is not required, see here

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