highComponent.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import React, { Component } from 'react'
  2. import {
  3. StyleSheet,
  4. View,
  5. Image,
  6. Text,
  7. StatusBar,
  8. Alert,
  9. ImageBackground,
  10. PixelRatio,
  11. TouchableOpacity,
  12. ScrollView,
  13. } from 'react-native'
  14. import Icon from '../../components/Iconfont/Iconfont'
  15. function getDisplayName(component) {
  16. return component.displayName || component.name || 'Component'
  17. }
  18. // 属性代理 - 高阶
  19. export function ppHOC(WrappedComponent) {
  20. return class PP extends Component {
  21. static displayName = `HOC(${getDisplayName(WrappedComponent)})`
  22. constructor(props) {
  23. super(props)
  24. this.state = {
  25. name: '',
  26. }
  27. this.onNameChange = this.onNameChange.bind(this)
  28. }
  29. onNameChange(event) {
  30. this.setState({
  31. name: event.target.value,
  32. })
  33. }
  34. render() {
  35. const newProps = {
  36. name: {
  37. value: this.state.name,
  38. onChange: this.onNameChange,
  39. },
  40. }
  41. return <WrappedComponent {...this.props} {...newProps} />
  42. }
  43. }
  44. }
  45. // 反向继承 - 高阶
  46. export function extHOC(WrappedComponent) {
  47. return class Inheritance extends WrappedComponent {
  48. componentDidMount() {
  49. // 可以方便地得到state,做一些更深入的修改。
  50. alert(this.state, 222)
  51. }
  52. render() {
  53. return super.render()
  54. }
  55. }
  56. }