可触摸的不透明度功能,在应用程序启动时立即调用

时间:2018-10-08 10:47:48

标签: javascript react-native

我是新手,对js做出反应,我对下面的代码有疑问。作为可触摸不透明度的onpress属性值提供的功能是在应用程序启动时调用而不会触摸可触摸不透明度。任何人都可以解释屏幕后面发生的事情。有关详细信息,请参见在线方法中的hello方法注释。

export default class FirstClass extends Component {  

  hello(){  // this function is called at launch of application 
            // itslef .I know if i can use fat arrow function or 
            // bind function to invoke this wont call at the start 
            // of application.Can anyone explain why its calling
            // automatically in this case and what is the this 
            // refers to in this method in this case.
    console.log('Hai from method hello');
  }

  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity onPress={this.hello()}>
          <Text>FirstScreen</Text>    
        </TouchableOpacity>
      </View>
    );
   }
  }

3 个答案:

答案 0 :(得分:2)

之所以会发生这种情况,是因为您以渲染方式立即在渲染时调用该函数。

<TouchableOpacity onPress={this.hello()}> // This means you are directly invoking the function when the component renders. It is called as soon as the render happens.

vs

<TouchableOpacity onPress={() => this.hello()}> // You are referencing a function to React to call later when the actual event happens.

另一种说法:onPress需要一个功能,对吗?您没有传递函数,因为在您的情况下this.hello()不返回函数。您只需调用该函数即可。这是在渲染时发生的。

第二种方式:() => this.hello()实际上传递了一个函数。通过按下按钮,您可以调用传递给它的功能。

答案 1 :(得分:2)

让我们对此进行解释:

第一<TouchableOpacity onPress={this.hello}>

=没有用()进行函数调用(这是导致错误的实际原因)

=不需要.bind(this)

=无需在组件创建中使用 lambda () => this.hello()

由于性能问题,这两种方法都被视为有害的反模式。

第二

hello = () => { ... }

= 范围将保持正确,因此无需绑定

答案 2 :(得分:0)

之所以不触摸按钮就调用该方法的原因是,因为最后有(),这基本上是一个函数调用。通过this.hello传递函数,通过this.hello()传递函数调用,并传递该函数返回的值。

this.hello()更改为this.hello.bind(this)