Render-props mode in react

      In the process of front-end development, if we encounter two components with the same or similar functions, what should we do? Reuse similar functions? What to reuse? state, the method of operating state.

      There are two ways: render props mode, higher-order components (HOC). These two methods are not new APIs, but fixed patterns that have evolved using React's own unique coding skills. Next, we will take the render-props pattern as an example to demonstrate its use process step by step.

      case study

      Let's take the mouse movement to obtain the coordinates as an example. This case is an unoptimized code. We found that the ui is limited to the render.



      Analysis of optimization ideas


      Idea: Encapsulate the state to be reused and the method of operating state into one component

      How to get the state reused in the component

      When using components, add a prop whose value is a function, and get it through function parameters


      How to render to any UI, use the return value of this function as the UI content to be rendered


      Steps for usage

      Create a Mouse component and provide reused logic code in the component

      Expose the state to be reused as a parameter of the props.render(state) method to the outside of the component

      Use the return value of props.render() as the content to be rendered


      Sample demo


      children instead of render attribute

      Note: It is not that the mode called render props must use the prop named render, in fact, you can use props with any name

      The technology that prop is a function and tells the component what content to render is called: render props mode

      Recommendation: Use childre instead of render attribute


      The render inside the Mouse component is modified to:


      Optimized code

      It is recommended to add props verification to render-props mode


      Unbind event when the component is removed


This article is from Qianfeng Education WEB Front-end College , please indicate the source for reprinting

Guess you like