我有一个带有本地App.js
的react-native应用程序:
import { createStackNavigator } from 'react-navigation';
class App extends Component {
render() {
return <AppStack {..this.props} />
}
}
export withAuth(App)
高阶组件
withAuth
将user
和authenticating
Prop 添加到App
:const withAuth = (Component) =>
class WithAuth extends React.Component {
constructor(props) {
super(props)
this.state = {
authenticating: true,
user: false
}
}
componentDidMount() {
// authenticating logic ...
firebase.auth().onAuthStateChanged(user => {
if (user)
this.setState({
authenticating: false,
user: user
})
else
this.setState({
authenticating: false
})
})
}
render() {
return (<Component user={this.state.user} authenticating={this.state.authenticating} {...this.props} />)
}
}
AppStack
是:const AppStack = createStackNavigator(
{ AppContainer, Profile },
{ initialRouteName : 'AppContainer' }
)
请注意,没有代码将
props
传递的class App
传递给AppContainer
和Profile
。因此,
user
中的authenticating
和AppContainer
Prop 是未定义的。class AppContainer extends Component {
// this.props.user is false and this.props.authenticating is true
componentDidMount() {
console.log(`Debug Did mount with user: ${this.props.user}`, this.props.authenticating)
}
render() {
// if I `export withAuth(AppContainer)`, then this prints the user information. but not if I log inside `componentDidMount`
console.log(`Debug loaded with user: ${this.props.user}`, this.props.authenticating)
return <Text>'hello world'</Text>
}
}
export default AppContainer
我可以将
AppContainer
包装在withAuth
内并执行export default withAuth(AppContainer)
,但是AppContainer
无法读取this.props.user
中的componentDidMount
属性,而只能读取render() { ... }
中的属性。理想情况下,我想从
user
传递authenticating
和AppStack
属性,我该怎么做?注意:目前,我尽可能不使用
redux
。这是一个简单的应用程序。 最佳答案
您可以通过screenProps
将 Prop 从高级组件传递到子屏幕。例:
const withTest = Component => (
class WithTest extends React.Component {
render() {
return (<Component screenProps={{ user: "abc" }} />);
}
});
检查Navigator Props以获得更多详细信息。