反应js中的自调用功能? (如常规javascript)

时间:2017-06-05 16:49:38

标签: javascript reactjs jsx

我想调用function good而不从事件中调用它。它应该在页面打开后立即运行,就像在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;

2 个答案:

答案 0 :(得分:3)

几点:

1。您需要使用this关键字来调用任何其他函数中的任何函数。

2. 要将js代码放入JSX,我们需要使用{}

像这样写:

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>
        );
    }
}

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

查看这些答案以获取更多详细信息:

How does the "this" keyword work?

What do curly braces mean in JSX (React)?

答案 1 :(得分:0)

您还可以将生命周期方法用作componentDidMount(){}或componentWillMount(){}。

在安装组件之前将触发

componentWillMount,并且在安装组件后将触发componentDidMount()。