类似 vue 的 mixins

  • 定义withFetch.jsx 文件, 内部使用公共部分
  1. import React, {Component} from 'react';
  2. // 公共部分放在这里, mixins
  3. const withFetch = (count) => (View) => {
  4. return class extends Component {
  5. constructor(){
  6. super()
  7. this.state= {
  8. loading: true,
  9. count: 0
  10. }
  11. }
  12. componentDidMount(){
  13. this.setState({
  14. count: count
  15. })
  16. setTimeout(()=>{
  17. this.setState({
  18. loading:false
  19. })
  20. }, 5000)
  21. }
  22. render() {
  23. if(this.state.loading) {
  24. return <div>loading.......</div>
  25. }else{
  26. return <View count={this.state.count}></View>
  27. }
  28. }
  29. }
  30. }
  31. export default withFetch
  • test.jsx
  1. import React from 'react';
  2. import withFetch from './withFetch'
  3. const Banner = withFetch(123)(props => {
  4. return (
  5. <div>
  6. <p>
  7. 获取到数据:
  8. {props.count}
  9. </p>
  10. </div>
  11. )
  12. })
  13. export default Banner