最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - Self invoking function in react js ? (as in regular javascript) - Stack Overflow

programmeradmin4浏览0评论

I want to invoke the function good without calling it from a event. It should run as soon as page opened just like in the self invoking javascript function. Here is an example

import React from 'react';

class App extends React.Component {

   good(){
      console.log('I was triggered during good')
   }

   render() {
       console.log('I was triggered during render')
       return(
          <div>
             good();  
          </div>
      );
   }
}

export default App;

I want to invoke the function good without calling it from a event. It should run as soon as page opened just like in the self invoking javascript function. Here is an example

import React from 'react';

class App extends React.Component {

   good(){
      console.log('I was triggered during good')
   }

   render() {
       console.log('I was triggered during render')
       return(
          <div>
             good();  
          </div>
      );
   }
}

export default App;
Share Improve this question edited Jun 5, 2017 at 16:56 Mayank Shukla 105k19 gold badges162 silver badges145 bronze badges asked Jun 5, 2017 at 16:49 Sambit Kumar SahuSambit Kumar Sahu 111 gold badge1 silver badge3 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Few Points:

1. You need to use this keyword to call any function from any other function.

2. To put js code inside JSX, we need to use {}.

Write it like this:

import React from 'react';

class App extends React.Component {

    good(){
        console.log('I was triggered during good')
        return <div> Hello </div>
    }

    render() {
        console.log('I was triggered during render')
        return(
            <div>
                {this.good()}
            </div>
        );
    }
}

Check React DOC: https://facebook.github.io/react/docs/introducing-jsx.html

Check these answers for more details:

How does the "this" keyword work?

What do curly braces mean in JSX (React)?

You can also use lifecycle methods as ponentDidMount(){} or ponentWillMount(){}.

ponentWillMount will be triggered before mounting of ponent and ponentDidMount() will be triggered after ponent has been mounted.

发布评论

评论列表(0)

  1. 暂无评论