hoc

  1. withRouter(withCounter(AnotherHoc))

render props

  1. class Counter extends Component {
  2. constructor(props) {
  3. super(props);
  4. this.state = { count: props.initCounter };
  5. }
  6. increase = () => this.setState(prevState => ({ count: prevState.count + 1 }));
  7. decrease = () => this.setState(prevState => ({ count: prevState.count - 1 }));
  8. render() {
  9. const { count } = this.state;
  10. return (
  11. <div>
  12. {this.props.children({
  13. count,
  14. increase: this.increase,
  15. decrease: this.decrease
  16. })}
  17. </div>
  18. );
  19. }
  20. }
  21. import Counter from "./renderPropCounter";
  22. const CompOne = ({ initCounter }) => (
  23. <Counter initCounter={initCounter}>
  24. {({ count, increase }) => (
  25. <div>
  26. Count: {count}
  27. <button onClick={increase}>+</button>
  28. </div>
  29. )}
  30. </Counter>
  31. );

hooks

  1. // count.js
  2. import { useState } from "react";
  3. const useCounter = initCount => {
  4. const [count, setCount] = useState(initCount);
  5. return [
  6. count,
  7. () => setCount(count => count + 1),
  8. () => setCount(count => count - 1)
  9. ];
  10. };
  11. // main.js
  12. import useCounter from "./useCounter";
  13. const CompOne = ({ initCounter }) => {
  14. const [count, increase] = useCounter(initCounter);
  15. return (
  16. <div>
  17. Count: {count}
  18. <button onClick={increase}>+</button>
  19. </div>
  20. );
  21. };