我有一个顶级App.js
的React-native应用程序:
import { createStackNavigator } from 'react-navigation';
class App extends Component {
render() {
return <AppStack {..this.props} />
}
}
export withAuth(App)
高阶元素withAuth
在user
上添加authenticating
和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
的{{1}}传递。
因此Profile
中的user
和authenticating
道具是未定义的。
AppContainer
我可以将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
属性,只能读取{ {1}}。
理想情况下,我想从componentDidMount
传递render() { ... }
和user
属性,我该怎么做?
注意:目前,我尽可能不使用authenticating
。这是一个简单的应用程序。
答案 0 :(得分:1)
您可以通过screenProps
将道具从高阶组件传递到子屏幕。示例:
const withTest = Component => (
class WithTest extends React.Component {
render() {
return (<Component screenProps={{ user: "abc" }} />);
}
});
检查Navigator Props以获得更多详细信息。