简体   繁体   中英

React Native ref is undefined when re-rendering a component

I have a problem with refs on React Native. This is a simplified version of my code:

class Main extends React.Component {

    constructor(props) {
        ...
        this.refs = {};
    }

    render() {
        if(this.state.page=="index") {
            return(
                <View>
                    <FlatList ref={flatlist => this.refs.flatlist = flatlist}> ... </FlatList>
                    <MyActionButton flatlist={this.refs.flatlist}/>
                </View>
            )

        } else if (this.state.page="text"=){
            return(
                <Text> ... </Text>
            )
        }
    }
}


class MyActionButton extends React.Component {
    render(
        return(
            <ActionButton>
                <ActionButtonItem onPress={() => {
                    console.log("AB props", this.props)
                }} />
            </ActionButton>
        )
    )
}

The app starts with this.state.page = "index" so when I press MyActionButton I see the log as expected, and things seem to work:

'AB props', {flatlist: {A LOT OF STUFF HERE}}

However If I change the state.page to "text" and then come back to "index" again, when I press MyActionButton I get:

'AB props', {flatlist: undefined}

I'm not sure why that prop gets undefined and how to fix it to make it point to the actual FlatList.

I don't like very much, but I managed to get it working by changing the reference to a getter funcion

class Main extends React.Component {

    constructor(props) {
        ...
        this.refs = {};
    }

    getFlatList() {
        return this.refs.flatlist;
    }

    render() {
        if(this.state.page=="index") {
            return(
                <View>
                    <FlatList ref={flatlist => this.refs.flatlist = flatlist}> ... </FlatList>
                    <MyActionButton flatlist={this.getFlatList.bind(this)}/>
                </View>
            )

        } else if (this.state.page="text"=){
            return(
                <Text> ... </Text>
            )
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM