在React Native中的自定义组件上调用onPress

时间:2018-08-28 19:32:25

标签: javascript reactjs react-native expo

该如何解决?我的ModalScreen中包含一个自定义的Button组件。似乎一切正常,但是onPress函数起作用了。它似乎由于某种原因失去了作用域,因此我无法引用Target Framework甚至无法向该函数添加参数。我在这里想念什么?

this

Button.js

import React from 'react';
import {
  Text,
  View,
} from 'react-native';

import Styles from 'app/constants/Styles';
import Button from 'app/components/Button';

export default class ModalScreen extends React.Component {

    onBtnPress() {
        console.log('dfsdfsdf'); /// << this gets consoled out just fine
        //this.props.navigation.navigate('Main'); <<<< this won't work
    }

    render() {
        return (
            <View style={Styles.center}>

                <Text>MOdalScreen</Text>
                <Button label='Gå vidare' onPress={ this.onBtnPress }/>

            </View>
        );
    }
}

1 个答案:

答案 0 :(得分:2)

您是对的,它失去了范围。您只需要以某种方式将范围绑定到handle函数,然后再将其提供给Button组件即可。一种流行的方法是使用方便的箭头功能:

<Button label='Gå vidare' onPress={ () => this.onBtnPress() }/>

或者您可以在构造函数中使用bind:

export default class ModalScreen extends React.Component {
    constructor(props) {
        super(props);
        this.onBtnPress = this.onBtnPress.bind(this)
    }

    onBtnPress() {
        console.log('dfsdfsdf'); /// << this gets consoled out just fine
        //this.props.navigation.navigate('Main'); <<<< this won't work
    }