How to pass state of one component to another in react native?

前端 未结 1 1973
野趣味
野趣味 2021-01-07 07:46

I am working on react native and I have two files in first I run geolocation function to get the coordinates and assign it to states. Now I want to access this

1条回答
  •  迷失自我
    2021-01-07 08:31

    After setting the state inside your MapScreen Component , You need to make sure to pass it as a props to your Hospital Component

    So inside your MapScreen you need to import the Hospital component like (you can amend the link accordingly) :

    import View from '../components/Hospital'
    

    Inside your MapScreen create a render function and pass state as a props to it (You can amend it accordingly , depending on which props you want to send down to the Hospital )

    export default class MapScreen extends React.Component { 
    
        render() {
            return (
    < Hospital view={this.state.mapInitialRegion}/>
    ) } }

    UPDATED :

    For checking if this.state is not empty or undefined you can do something like :

    export default class MapScreen extends React.Component { 
    
     let mapInitial;
    
     if(this.state.mapIntialRegion) {
    
       mapInitial = < Hospital view={this.state.mapInitialRegion}/>
        } else { mapInitial = 
    Loading ...
    } render() { return (
    {mapInitial}
    ) } }

    Now inside your Hospital Component you can access the Props via the object you passed inside your MapScreeen render function in this case I have passed view :

    this.props.view.mapInitialRegion

    or You can make use of destructing like :

    const { latitude , longitude} = this.props.view.mapInitialRegion

    0 讨论(0)
提交回复
热议问题