react-native-navigation的迁移库

docs-passing-data-to-components.mdx 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. ---
  2. id: passing-data-to-components
  3. title: Passing data to components
  4. sidebar_label: Passing data to components
  5. ---
  6. ## Initial props
  7. React components use [props](https://facebook.github.io/react-native/docs/props) to receive data when they are created. When displaying the [component](../api/layout-component) layout, you can pass initial props to components using the `passProps` property.
  8. In this example, we push the `UserProfile` screen and pass two initial props to it:
  9. ```js
  10. Navigation.push(this.props.componentId, {
  11. component: {
  12. name: 'UserProfile',
  13. id: 'PROFILE_SCREEN_ID'
  14. passProps: {
  15. name: 'John Doe',
  16. status: 'online'
  17. }
  18. }
  19. });
  20. ```
  21. :::tip Serialization
  22. passProps don't need to be serializable. You can use this mechanism to pass lambda functions or even React Components.
  23. :::
  24. ## Handling passProps in static options
  25. Each component can have a static options property which is used to configure the style properties of elements on the screen when that component is displayed.
  26. Static options can either be a simple object, or a function which accepts `passProps` as an argument. Sometimes when declaring components, not all style properties are known. For example, a user profile screen will usually have the user's name as the TopBar title text. Therefore the title must be configured dynamically when pushing the screen.
  27. Following the code example [above](passing-data-to-components#initial-props), lets see how to use props passed in the push command to set the TopBar title.
  28. ```jsx
  29. class UserProfileScreen extends React.Component {
  30. static options(props) {
  31. return (
  32. topBar: {
  33. title: {
  34. text: props.name
  35. }
  36. }
  37. );
  38. }
  39. }
  40. ```
  41. ## Updating props
  42. To update a component's props, use the [Navigation.updateProps()](../api/component#updateprops) command. Updating props triggers the component lifecycle methods related to [updating](https://reactjs.org/docs/react-component.html#updating).
  43. Notice that we're using the component `id` in order to update props of this specific instance of the component.
  44. ```js
  45. Navigation.updateProps('PROFILE_SCREEN_ID', {
  46. status: 'offline'
  47. });
  48. ```