render props

  1. class Wrapper extends React.Component {
  2. state = {
  3. count: 0
  4. };
  5. confirm = () => {
  6. window.alert(1)
  7. }
  8. // Increase count
  9. increment = () => {
  10. const { count } = this.state;
  11. return this.setState({ count: count + 2 });
  12. };
  13. // Decrease count
  14. decrement = () => {
  15. const { count } = this.state;
  16. return this.setState({ count: count - 1 });
  17. };
  18. render() {
  19. const { count } = this.state;
  20. return (
  21. <div>
  22. {this.props.render({
  23. increment: this.increment,
  24. decrement: this.decrement,
  25. confirm: this.confirm,
  26. count: count
  27. })}
  28. </div>
  29. );
  30. }
  31. }
  32. class App extends React.Component {
  33. render() {
  34. return (
  35. <Wrapper
  36. render={({ increment, decrement, confirm, count }) => (
  37. <div>
  38. <div>
  39. <h3>Render Props Counter</h3>
  40. </div>
  41. <div>
  42. <p>{count}</p>
  43. <button onClick={() => increment()}>Increment</button>
  44. <button onClick={() => decrement()}>Decrement</button>
  45. <button onClick={confirm}>confirm</button>
  46. </div>
  47. </div>
  48. )}
  49. />
  50. );
  51. }
  52. }
  53. ReactDOM.render(<App />, document.getElementById("root"));

useImperativeHandle + forwardRef

context