天天看點

React Native之内部方法常用幾種寫法和調用規則

1 簡單部分代碼

export default class App extends Component<Props> {
  render() {
    return (
        <View style={styles.container}>
        <View style={styles.welcome}>
                <Button onPress={this.showMsg}title='prees me showMsg'/> 
        <Button onPress={() => {this.showMessage()}}title='prees me showMessage'/> 
            </View>
        </View>
    );
  }
    //記得這裡調用的時候不需要加上()
    showMsg(){
    alert("showMsg(){}");  
    }
    
    //記得末尾加上分号,調用的時候也要加上()
    showMessage = () => {
        alert("showMessage = () => {}");
    };
}
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 10,
    textAlign: 'center',
    margin: 30,
  },
});      

2 分别點選上面代碼的2個按鈕效果如下

React Native之内部方法常用幾種寫法和調用規則
React Native之内部方法常用幾種寫法和調用規則