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

1次阅读

共计 3190 个字符,预计需要花费 8 分钟才能阅读完成。

最近会陆续分享我在应用 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 属性

革新结束,下期再会。

正文完
 0