【问题标题】:Self invoking function in react js ? (as in regular javascript)react js中的自调用函数? (如在常规 javascript 中)
【发布时间】:2017-11-06 12:16:29
【问题描述】:

我想调用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;

【问题讨论】:

    标签: javascript reactjs jsx


    【解决方案1】:

    几点:

    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 文档:https://facebook.github.io/react/docs/introducing-jsx.html

    查看这些答案了解更多详情:

    How does the "this" keyword work?

    What do curly braces mean in JSX (React)?

    【讨论】:

    • 很好解释... :)
    • 这真的很有帮助
    【解决方案2】:

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

    componentWillMount 会在组件挂载前触发,componentDidMount() 会在组件挂载后触发。

    【讨论】:

    • 谢谢。我会尝试这些。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-21
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多