React高阶用法之Render Props

最近会陆续分享我在使用React的过程总结的一些比较高阶的使用方法,这些方法可以提升代码的可复用性,也让代码看起来更加简洁明晰。今天要讲的是Render Props,很多人可能都知道react的这个特性,但在实际项目中不知道如何用起来。刚好这两天的一个项目中用到了它,所以借机分享一下。

什么是Render Props

“render prop”是指一种在React组件之间使用值为函数的prop共享代码的技术

这个概念听上去有点拗口,我们拆开了看它。

  1. 首先它本质上是一个prop,是用来父子组件之间传递数据用的
  2. 其次这个prop传递的值是一个函数
  3. 最后它取名render props,是因为它通常是用来render(渲染)某个元素或组件

比如官网给出的示例:

<DataProvider render={data => (
  <h1>Hello {data.target}</h1>
)}/>

我们给 这个子组件传递了一个叫 render 的prop,这个prop的值是一个函数,它返回了一个 h1 元素。然后我们可以假装实现一下这个 组件:

class DataProvider extends React.Component {
    
    
    state = {
        data: {
            target: 'World'
        }
    }
    render() {
        return this.props.render(this.state)
    }
}

最终我们的 DataProvider 组件渲染的结果就是 <h1>Hello World</h1> 。有同学可能会有疑问,为什么要费这么大周折?直接把 h1 元素写在 DataProvider 组件里不也可以吗?

这里就要讲到代码的可复用性了,假如下次我们希望 DataProvider 组件渲染的结果就是 Hello World 呢?难道又去修改 DataProvider 组件吗?有了render props,我们就可以动态地决定 DataProvider 组件内部要渲染的元素,同时这个元素还可以使用到 DataProvider 组件内部的数据。

实际项目案例

下面讲一个实际的项目案例,下图中我们有一个横向滚动的 ScrollView 组件,这个组件本身是个很普通的

元素, 只不过样式上加了 overflow-x: scroll 所以可以横向滚动起来。产品同学说滚动区域的下方要有进度点指示,从而告诉用户总共有几个产品,已经现在滚到第几个产品了。

明确了产品需求以后,我们就开始来实现,首先看下第一版:

class demo extends Component {
     
     
    state = {
      activeIndicator: 0,
      list: []
    }
    
    onScroll = () => {
        const { list } = this.state;
        const container = findDOMNode(this.refs.container);
        ...
        const itemVisibleLengthInContainer = list.map((item, index) => {
          const node = findDOMNode(this.refs[`item-${index}`]);
           ...
        });
        this.setState({
          activeIndicator: active,
        });
    };
    
    render() {
        const { list, activeIndicator } = this.state;
        return (
             <ScrollView
                ref="container"
                horizontal={ true}
                onScroll={this.onScroll}
             >
                {list.map((item,i) => (
                    <ProductItem
                        ref={`item-${i}`}
                        data={item}
                    />
                 ))}
                 
             </ScrollView>
             <Indicator list={list} active={activeIndicator} />
        )
    }
}

ok,需求我们已经实现了。实现逻辑就是给 ScrollView 组件添加一个 onScroll 事件,每当滚动的时候,会先计算 ScrollView 容器的位置信息,和每一个 ProductItem 的位置信息,算出现在哪个 ProductItem 在 ScrollView 容器中所占比例最高,从而得出现在应该高亮的 activeIndicator 。

不过现在有个问题哦,给 ScrollView 组件增加进度指示器这个功能,更像是 ScrollView 组件应该支持的一个功能,而不是直接写在业务代码里。所以我们应该提供一个新组件 ScrollViewWithIndicator ,让它去处理进度指示器的问题,从而跟业务解耦。

class ScrollViewWithIndicator extends Component {
     
     
    state = {
      activeIndicator: 0,
    }
    
    onScroll = () => {
        const { list } = this.props;
        const container = findDOMNode(this.refs.container);
        ...
        const itemVisibleLengthInContainer = list.map((item, index) => {
          const node = findDOMNode(this.refs[`item-${index}`]);
           ...
        });
        this.setState({
          activeIndicator: active,
        });
    };
    
    render() {
        const [{ list, children, ...restProps } , { activeIndicator }] = [this.props, this.state];
        return (
             <ScrollView
                ref="container"
                {...restProps}
                onScroll={this.onScroll}
             >
                {list.map((item,i) => (
                    <div ref={`item-${i}`}>   
                        {children(item}
                    </div>
                 ))}
                 
             </ScrollView>
             <Indicator list={list} active={activeIndicator} />
        )
    }
}

然后我们的业务代码就可以简化了:

class demo extends Component {
     
     
    state = {
      list: []
    }
    render() {
        const { list } = this.state;
        return (
              <ScrollViewWithIndicator
                horizontal={ true}
                list={list}
             >
              {child => <ProductItem {...child} />}  //(*)
             </ScrollViewWithIndicator>
        )
    }
  1. 仔细看业务代码demo组件,我们一共给ScrollViewWithIndicator组件传递了多少个props?答案是三个!分别是horizontal, list ,children,大家千万别忘了this.props.children也是一个props哦

  2. 再仔细看第(*)这句话,我们给ScrollViewWithIndicator组件传递一个叫children的prop,同时这个prop是一个函数,返回了一个组件(元素),这就是我们所说的render props啊

  3. 为什么list.map这个数组的遍历要写在ScrollViewWithIndicator组件内部,而不是业务组件demo里呢?因为我们在onScroll 事件回调函数里要计算每一个商品item的位置,也就是要拿到商品item的ref属性,所以把数组的遍历写在ScrollViewWithIndicator 组件内部方便我们显性给每一个商品item声明ref属性

以下资料需要的可以加qq群:954854084或者关注微信公众号:晨曦大前端

以下资料需要的可以加qq群:954854084或者关注微信公众号:晨曦大前端

以下资料需要的可以加qq群:954854084或者关注微信公众号:晨曦大前端

猜你喜欢

转载自blog.csdn.net/CHENXI_0/article/details/108300521