Devin
Devin

Reputation: 33

Why react component?

In the react component, props is received, but the props values is undefined.

My component looks like this

class NavRoot extends Component {
    constructor (props) {
        super(props)

        this._handleNavigate = this._handleNavigate.bind(this)
    }

    _renderScene (props) {
        const { route } = props.scene
        if (route.key == 'home') {
            // here is the problem: In Home component, props received Object {_handleNavigate: undefined}
            return <Home _handleNavigate={this._handleNavigate} />
        }
    }

    // handle navigation between scene
    _handleNavigate (action) {
        switch (action && action.type) {
            case 'push':
                this.props.pushRoute(action.route)
                return true;
            case 'back':
            case 'pop':
                return this._handleBackAction()
            default:
                return false;
        }
    }

    render() {
        return (
            <NavigationCardStack
                style={{flex: 1}}
                navigationState={this.props.navigation}
                onNavigateBack={this._handleBackAction}
                renderScene={this._renderScene} />
        )
    }
}

function mapStateToProps (state) {
    return {
        navigation: state.navReducer
    }
}

export default connect(
    mapStateToProps,
    {
        pushRoute: (route) => push(route),
        popRoute: () => pop()
    }
)(NavRoot)

And this is what Home component looks like:

class Home extends Component {
    constructor(props) {
        super(props);
    }
    render() {
    return (
    <View style={styles.container}>
        <Text style={styles.title}>Home</Text>
        <Button onPress={this.props._handleNavigate(route)} label='Go to About' />
    </View>
    )
    }
}

When I click the button, it reports _handleNavigate is undefined. In Home component, props received Object {_handleNavigate: undefined}

Upvotes: 0

Views: 62

Answers (1)

chenkehxx
chenkehxx

Reputation: 1625

please change your constructor function:

constructor (props) {
        super(props)

        this._handleNavigate = this._handleNavigate.bind(this)
        this. _renderScene = this. _renderScene.bind(this);
    }

because the context of _renderScene is not the context of NavRoot.

Upvotes: 2

Related Questions