autobind-decorator icon indicating copy to clipboard operation
autobind-decorator copied to clipboard

this.props is undefined on autobind decorator

Open flexy1994 opened this issue 6 years ago • 2 comments

I've got some problems while using the autobind decorator on React Native.

I use the newest release v2.4. react-native: 0.54.0

Example:

I've implemented two Screens:

First with button to Navigate to the second screen.

Second screen is rendering a component e.g. a customized TouchableOpacity (CustomTouchableOpacity).

The CustomTouchableOpacity got an onPress prop and implements a function that is calling this.props.onPress from the ReactNative given onPress function of TouchableOpacity.

After multiple Transitions (navigate with ReactNavigation) between the First and Second Screen, this.props of the CustomTouchableOpacity is undefined.

import autobind                                from 'autobind-decorator';
import React                                     from 'react';
import { View }                                  from 'react-native';
import CustomTouchableOpacity   from '../components/CustomTouchableOpacity';

class SecondScreen extends React.Component {
    constructor (props) {
        super(props);
    }

    @autobind
    onPress () {
        // do some stuff and navigate back (pop)
    }

    render () {
        return (
            <View>
                <CustomTouchableOpacity
                    label={'Lorem'}
                    onPress={this.onPress}
                    />
            </View>
        )
    }
}

module.exports = SecondScreen;
// CustomTouchableOpacity
import autobind                      from 'autobind-decorator';
import React                           from 'react';
import { TouchableOpacity } from 'react-native';
import { Text }                         from 'react-native';

class CustomTouchableOpacity extends React.Component {
    constructor (props) {
        super(props);        
    }

    @autobind
    onPress () {
        if (this.props) {
            this.props.onPress();
        } else {
            alert('empty props');
        }
    }

    render () {
        return (
            <TouchableOpacity
                onPress={this.onPress}
            >
                <Text>{this.props.label}</Text>
            </View>
        );
    }
}

module.exports = CustomTouchableOpacity;

This problem only exists if im NOT connected to the Remote Debugger.

On using the traditional this.onPress = this.onPress.bind(this) binding the component never loses the props.

flexy1994 avatar Feb 12 '19 15:02 flexy1994

Can you try https://github.com/andreypopp/autobind-decorator/pull/79?

stevemao avatar Feb 12 '19 22:02 stevemao

Please try https://github.com/andreypopp/autobind-decorator/pull/57 also

stevemao avatar Feb 13 '19 03:02 stevemao