如何将数据传递给 class 之外的组件

how to pass data to a component which is outside of the class

我通过将用户名作为参数从我以前的页面中获取用户名,并且我在我的新页面中获取数据作为 this.props.userName

现在我想将此值传递给我在选项卡视图中使用的其他组件。

我正在使用 React Native router fluxreact native tab view.

问题:因为我使用常量来存储 class 上方的组件,所以我无法将 props 数据传递给该组件

const FirstRoute = () => <Profile />;
const SecondRoute = () => <Video />;
const ThirdRoute = () => <View style={{flex: 1, backgroundColor: 'rgba(0,0,0,0.2)'}} />;

export default class Dashboard extends React.Component {

    constructor(props) {
        super(props);
        console.log(this.props.userName, 'props'); // want to pass this data to FirstRoute i.e: in <Profile />
    }

    state = {
        index: 1,
        routes: [
            {key: 'first', icon: 'md-contact'},
            {key: 'second', icon: 'md-videocam'},
            {key: 'third', icon: 'md-arrow-dropright-circle'},
        ],
    };

    _renderScene = SceneMap({
        first: FirstRoute,
        second: SecondRoute,
        third: ThirdRoute
    });

    render() {
        return (
            <TabView
                tabBarPosition='bottom'
                navigationState={this.state}
                renderScene={this._renderScene}
                onIndexChange={this._handleIndexChange} // not included to decrease the code length
                initialLayout={initialLayout} // not included to decrease the code length
            />
        );
    }
}

您可以将 _renderScene 函数扩展为

_renderScene = ({ route }) => {
  switch (route.key) {
    case 'first':
      return <Profile userName={this.props.userName} />;
    case 'second':
      return <Video />;
    case 'third':
      return <View style={{flex: 1, backgroundColor: 'rgba(0,0,0,0.2)'}} />;
    default:
      return null;
  }
};