react js中的自调用函数?(就像在常规 javascript 中一样)

1 javascript jsx reactjs

我想在function good不从事件中调用它的情况下调用它。它应该在页面打开后立即运行,就像在self invoking javascript function. 这是一个例子

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;
Run Code Online (Sandbox Code Playgroud)

May*_*kla 5

几点:

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>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

“this”关键字如何工作?

JSX (React) 中的大括号是什么意思?