I have been learning jQuery for quite sometime and so far it's been good. But there is one thing I am stuck on. I did try to get answers before putting this question up but those weren't helpful in getting me the solution I was really looking for.
I am trying to call a jQuery function from one of my jQuery function files. Let me give you an example of what I am trying to achieve here.
I have my react_component.js which contains react and jsx code.
React_component.js
import React from 'react';
import {render} from 'react-dom';
export class Home_page extends React.Component{
render(){
return(
<section className="home-sections">
<div className='home-div'>
<h1>Hello, I am home page</h1>
</div>
</section>
);
}
componentDidMount(){
//console for some reason doesnt work here.
animate_component(); //Jquery function call
}
}
jQuery file home.js
animate_component(){
alert("animate the 'sections' component");
//Some animation code needs to execute
}
Errors I get:
Uncaught ReferenceError: animate_component is not defined
at React_component.componentDidMount
Basically I want to execute .js files specific to each component (page). I am trying to build a SPA using react and with jquery i have added some on-screen animations which I want to execute only when the respective component gets rendered. So when home page is rendered, only run the code from home.js, and not others. Same goes for other pages.
Also, just to make it more clear, i have bundled several .js files into one. For e.g, scripts for home page have been bundled altogether, same for other pages, so to picture this without react, it would be, for home page I am running only 1 bundled home.js file instead of multiple .files, for about page, 1 about.js file. So to re-iterate my question, when home page is rendered, run functions only from home.js, when about page is rendered, run functions only from about.js.
答案 0 :(得分:0)
As suggested in this medium post, you can import jquery as import $ from ‘jquery’;
, define your function using jquery (he makes one called handleToggle
), and then integrate it in dom like onClick={this.handleToggle}
.
Note that using ids and classes to manipulate dom simultaneously is discouraged. Also a discuss thread that might be useful here There seems to be lots of materials around.