实现组件复用的编码技巧

组件的复用

复用相似的功能,复用状态

render-props 模式

  1. // 创建一个新的组件 使用组件时添加一个函数(任意名称)作为值 该函数的返回值作为要渲染的内容
  2. <Mouse render={(mouse)=>{}} />
  3. class Mouse extends React.Component{
  4. state = {
  5. a:0
  6. }
  7. // 事件处理程序
  8. handle = () =>{
  9. this.setState({
  10. a:'新状态'
  11. }
  12. }
  13. render(){
  14. // 渲染传入的函数的返回值
  15. this.props.render(this.state)
  16. }
  17. }
  18. // children 子节点模式 插槽
  19. <Mouse>{mouse=>(<div></div>)}</Mouse>
  20. render(){
  21. // 渲染传入的函数的返回值
  22. this.props.children(this.state)
  23. }
  24. }

高阶组件 (HOC)

使用包装模式 : 将一个组件封装为一个包装 使用这个组件包裹其他需要使用这个功能的组件
高阶组件是一个函数,接收要包装的组件 返回增强后的组件
这个函数会创建一个类组件 这个组件中提供复用逻辑的代码,通过prop将复用的状态传递给被包装的组件

  1. // 创建函数 使用with开头
  2. // 指定参数,参数就是组件 名字以大写字母开头
  3. const withXXX = Wrate => {
  4. // 创建一个类组件
  5. class Mouse extends React.Component{
  6. state={
  7. a:1
  8. }
  9. // 渲染参数传递的组件
  10. render(){
  11. render <Wrate {...this.state}></Wrate>
  12. }
  13. }
  14. // 返回组件
  15. return Mouse
  16. }
  17. // 使用
  18. // 调用函数 将要加强的组件作为参数传递
  19. withXXX(组件)