2017-06-05 76 views
0

我想调用function good而不从事件中调用它。它应该在页面打开后立即运行,就像在self invoking javascript function中一样。 Here is an example反应js中的自我调用函数? (如正常的javascript)

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; 

回答

3

几点:

您需要使用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> 
     ); 
    } 
} 

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

检查这些问题的答案更多细节:

How does the "this" keyword work?

What do curly braces mean in JSX (React)?

+0

很好解释... :) – VivekN

+0

真的有帮助 –

0

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

componentWillMount将在安装组件之前触发,componentDidMount()将在安装组件后触发。

+0

谢谢。我会尝试这些。 –