在类构造函数内部还是在组件类外部添加事件侦听器?

时间:2020-02-04 19:01:28

标签: javascript react-native

我的React Native(0.61.5)应用程序中有一个组件SplashScreenSplashScreen中需要一个事件监听器。尝试了以下两种添加事件侦听器的方法:

import nodejs from 'nodejs-mobile-react-native';

console.log("Nodejs obj : ", nodejs);
nodejs.start("main.js");
nodejs.channel.addListener(
"message",
(msg) => {
    alert("From node: " + msg);
    console.log("Message from nodejs : ", msg);
},
this
);

class SplashScreen extends React.Component {
..........
}

另一种方法是在类构造函数中添加事件侦听器:

import nodejs from 'nodejs-mobile-react-native';

class SplashScreen extends React.Component {

    constructor(props) {
        super(props);
        this._isMounted = false;

        this.state = {
            idx:1,
        };

        console.log("Nodejs obj : ", nodejs);
        nodejs.start("main.js");
        nodejs.channel.addListener(
        "message",
        (msg) => {
            alert("From node: " + msg);
            console.log("Message from nodejs : ", msg);
        },
        this
        ); 

      };
.....
}

两个代码都可以正常工作。从代码的角度来看,两者之间是否有任何区别,例如模式和性能?

0 个答案:

没有答案