React的一些高级用法(3)

139 阅读1分钟

Render Props 模式

React官网的解释: Render Props是指一种在 React 组件之间使用一个值为函数的 prop 共享代码的简单技术。 React 官网介绍

其实简单来说就是组件的某个props属性是一个函数,并且这个props函数会在组件内部被调用并返回参与渲染React元素

Render Props 模式主要是解决代码逻辑复用问题,并把组件内部状态暴露出去,让使用者根据这些状态去自定义渲染

demo

import * as React from "react";

const Test = (props) => {
  const { children } = props;
  const [count, setCount] = React.useState(0);
  return (
    <>
      <button
        onClick={() => {
          setCount(count + 1);
        }}
      >
        {count}
      </button>

      {children(count)}
    </>
  );
};

const App: React.FC = () => {
  return (
    <>
      <Test>
        {(count) => {
          if (count > 2) {
            return <div>count大于2的情况</div>;
          } else {
            return <div>count不大于2的情况</div>;
          }
        }}
      </Test>
    </>
  );
};

export default App;

Test组件的子组件children是一个函数,在Test组件内部会调用这个函数,并把count这个状态暴漏出去,这样子组件就可以根据count去自定义渲染内容。

Render Props模式还有另外一种实现形式。
import * as React from "react";

const Test = (props) => {
 const { render } = props;
 const [count, setCount] = React.useState(0);
 return (
   <>
     <button
       onClick={() => {
         setCount(count + 1);
       }}
     >
       {count}
     </button>

     {render(count)}
   </>
 );
};

const App: React.FC = () => {
 return (
   <>
     <Test
       render={(count) => {
         if (count > 2) {
           return <div>count大于2的情况</div>;
         } else {
           return <div>count不大于2的情况</div>;
         }
       }}
     />
   </>
 );
};

export default App;

这种是Test 组件接受一个普通的renderporps(props的名字可以是任意的,比如a,调用就是a(count)),然后调用这个render拿到要渲染的内容,其实和上面demo种的children本质是一样的。

像在react-router v5Route组件它会接受children component renderprops, 在内部也是会通过Render Props 模式去获取要渲染的内容。

L1VzZXJzL3poYW5nZnV5aW5nL0xpYnJhcnkvQXBwbGljYXRpb24gU3VwcG9ydC9EaW5nVGFsa01hYy8yODI1NDcxNjFfdjIvSW1hZ2VGaWxlcy8xNjU5MjYyNDQzNDIzXzE5NzI1ODhDLTBDOEMtNEQ3MC1CN0MxLUEyNjAwNENBNDQxNi5wbmc=.png