React Native-将参数传递给自定义导航器组件的同级

时间:2019-10-18 12:53:31

标签: react-native react-navigation react-navigation-stack

我具有如下所示的自定义导航器

const HomeStackNavigator = createStackNavigator({
    Home: HomeScreen,
    List: ListScreen,
    Details: DetailsScreen
},
    {
        initialRouteName: 'Home',
        defaultNavigationOptions: {
            header: null,
        }
    });

export default class CustomHomeStack extends React.Component {
    static router = HomeStackNavigator.router;
    render() {
        const { navigation } = this.props;

        return (
            <SafeAreaView style={{ flex: 1 }} forceInset={{ bottom: 'never' }}>
                <CustomHomeHeader /* breadCrumbParam={??} */ />
                <HomeStackNavigator navigation={navigation} />
            </SafeAreaView >
        );
    }
}

导航到“列表”或“详细信息”时,我可以将参数传递到下一个屏幕this.props.navigation.navigate('List', { breadCrumbParam: {id: theId, displayName: theName }} })

我还需要将相同的参数传递给CustomHomeHeader。 (类似于通过道具将参数传递给父/兄弟组件)。这可能吗?

1 个答案:

答案 0 :(得分:0)

好的,所以您需要做一些更改, 1.在导航堆栈中添加CustomHomeStack 2.将数据从家庭传递到家庭堆栈 3.从家庭堆栈中的家庭接收数据,并将其作为道具传递给CustomHomeHeader

因此下面的代码将是

const HomeStackNavigator = createStackNavigator({
    Home: HomeScreen,
    List: ListScreen,
    Details: DetailsScreen,
    CustomHomeStack:CustomHomeStack
},
    {
        initialRouteName: 'Home',
        defaultNavigationOptions: {
            header: null,
        }
    });

然后在家里假设您要在按钮clikc上调用homestack,

class Home extends Component{


onButtonClick(){
this.props.navigation.push('CustomHomeStack', { breadCrumbParam: 100 })

}


}

然后在customhomestack中,您需要使用导航参数,并通过存储在状态中将其传递给customgheader。

class CustomHomeStack extends Component {

 constructor(props){
        super(props);
this.state={
breadCrumbId:''
}
    }

componentDidMount(){
let breadCrumb = this.props.navigation.getParam("breadCrumbParam", "NO-ID");
this.setState({breadCrumbId:breadCrumb})
}

 render() {
        const { navigation } = this.props;

        return (
            <SafeAreaView style={{ flex: 1 }} forceInset={{ bottom: 'never' }}>
                <CustomHomeHeader  breadCrumbParam={this.state.breadCrumbId}  />
                <HomeStackNavigator navigation={navigation} />
            </SafeAreaView >
        );
    }


}

希望有帮助。否则发布问题