美文网首页
react复合组件封装思想(props截取)

react复合组件封装思想(props截取)

作者: lvzhiyi | 来源:发表于2018-06-21 22:40 被阅读0次

封装react组件经常会封装一些复合组件,比如手风琴,轮播图,等等……与常规组件不一样,复合组件经常会遇到一个问题,就是复合组件之间的通信,比如一个轮播组件Carousel我们可能会这样去封装:

轮播的父组件

class Carousel extends Component{
     //othen code……
      render() {
           return(
                  {this.props.children}
           )  
      }
}

轮播的子组件

class Item extends Component{
      //othen code……
      render() {
           return(
                  {this.props.children}
           )  
      }
}

使用的时候

    <Carousel>
          <Item>1</Item>
          <Item>2</Item>
          <Item>3</Item>
    </Carousel>

一般轮播会在滚动的时候把当前轮播的索引值暴露出去,此时就涉及到了复合组件父子组件的通信,我们可以这样做:

轮播的父组件

class Carousel extends Component{
     //othen code……
      render() {
           const newProps = [];
           React.Children.forEach(children, function(child: any, index) {
            let props = {
                key: index,
                onClick(){
                      child.props.onClick(index) 
                }
            };
            newChildren.push(React.cloneElement(child, props));
        });
           return(
                  {newChildren}
           )  
      }
}

轮播的子组件

class Item extends Component{
      //othen code……
      render() {
           return(
                 <div onClick={this.props.onClick}>
                          {this.props.children}
                 </div>
           )  
      }
}

使用的时候

    <Carousel>
          <Item onClick={(val)=>{console.log(val)}}>1</Item>    // 0 
          <Item>2</Item>
          <Item>3</Item>
    </Carousel>

以上父组件定义的变量props,就是截取子组件的props,可以对子组件的props进行增删改等操作,再次封装过后暴露出去,完成了复合组件子父组件之间的通信;

相关文章

网友评论

      本文标题:react复合组件封装思想(props截取)

      本文链接:https://www.haomeiwen.com/subject/fcfhyftx.html