props

158 阅读2分钟

props

在React中props是一个十分重要的机制,它的作用有很多很多,其中包括:

  • 数据的传递,在component的组件通信中有提到;
  • 配置和定制;
  • 事件的处理;
  • 组件的组合,例如插槽之类的;
  • 动态渲染

接下来将进一步分析props

认识props

props是什么?

简单的理解就是父组件绑定在它们标签里的属性/方法,最终会变成 props 传递给它们,但是也有特例,比如ref或key。

props可以是:

  • props 作为一个子组件渲染数据源。
  • props 作为一个通知父组件的回调函数。
  • props 作为一个单纯的组件传递。
  • props 作为渲染函数。
  • render props。
  • render component 插槽组件。

​ 在子组件中可以通过this.props访问到props。

监听props变化

在类组件中会用到之后lifeCycle中提到的两个生命周期函数,分别是componentWillReceiveProps用来监听props的变化,但是已经不推荐使用了,另一个就是getDerivedStateFromProps。

在函数式组件中使用的是useEffect,初始胡会默认执行一次。

props children模式

props插槽组件

<Container>
    <Children>
</Container>

在container中能够通过,props.children访问到Children组件,这种方式能根据需要控制 Children 是否渲染,Container能够根据自身情况通过React.cloneElement混入新的props。

render props

<Container>
   { (ContainerProps)=> <Children {...ContainerProps}  /> }
</Container>

当props.children是一个函数时,这是不能直接使用,必须传入一个props供children使用,这种方式能够根据需要控制 Children 渲染与否,可以将需要传给 Children 的 props 直接通过函数参数的方式传递给执行函数 children。

混合模式

​ 字面意思即在props.children中既有组件也有函数,那么就可以通过遍历props.children判断是否为element节点或者是一个函数,值得注意的是React提供了判断是否为react element的函数,为React.isValidElement。

​ 当为element节点时,通过React.cloneElement混入props;

​ 当为函数时,传递参数,执行函数。

对props的常见操作
  • 混入props,既在拿到父组件的props时处理完之后再往里添加自己的props,并且再传给子组件。
  • 抽离props,和混入props的操作恰好相反,从父组件的props中抽离某个属性再传给子组件。
  • 注入props
    • 显示注入:直接在子组件上绑定props;
    • 隐式注入:通过React.cloneElement对props.children克隆,同时注入props;

总结

学习到了props是什么,props的作用,操作props的一些技巧。