2017-06-05 72 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

謝謝。我會嘗試這些。 –