关于react.js:React高阶用法之Render-Props

最近会陆续分享我在应用React的过程总结的一些比拟高阶的应用办法,这些办法能够晋升代码的可复用性,也让代码看起来更加简洁清晰。明天要讲的是Render Props,很多人可能都晓得react的这个个性,但在理论我的项目中不晓得如何用起来。刚好这两天的一个我的项目中用到了它,所以借机分享一下。

什么是Render Props

The term “render prop” refers to a technique for sharing code between React components using a prop whose value is a function.

这个概念听下来有点拗口,咱们拆开了看它。

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

比方官网给出的示例:

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

咱们给<DataProvider>这个子组件传递了一个叫render的prop,这个prop的值是一个函数,它返回了一个h1元素。而后咱们能够伪装实现一下这个<DataProvider>组件:

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

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

这里就要讲到代码的可复用性了,如果下次咱们心愿DataProvider组件渲染的后果就是<span>Hello World</span>呢?难道又去批改DataProvider组件吗?有了render props,咱们就能够动静地决定DataProvider组件外部要渲染的元素,同时这个元素还能够应用到DataProvider组件外部的数据。

理论我的项目案例

上面讲一个理论的我的项目案例,下图中咱们有一个横向滚动的ScrollView组件,这个组件自身是个很一般的<div>元素, 只不过款式上加了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的地位信息,算呈现在哪个ProductItemScrollView容器中所占比例最高,从而得出当初应该高亮的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属性

革新结束,下期再会。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理