组合
- 组合再react中,是一种非常强大的组件复用的设计模式
- 语法基础:props可以传递任意类型的数据、包括jsx对象
- 再自定义组件的内部,可以嵌套jsx对象,再子组件中使用 props.children进行渲染
上下文
contex提供了一个无需为每层组件手动添加props,就能在组件树进行数据传递的方法
作用:用于在React组件树中进行数据传递,避免使用链式的props
上下文数据是单向传输的,只能从上到下
创建上下文:
// 创建一个上下文 const ThemeCtx = React.createContext(); // ThemeCtx.Provider包裹组件,value为传入的数据 <ThemeCtx.Provider value=> </ThemeCtx.Provider> // 组件内使用传入的数据 // 1. class TestContext extends React.Component { render () { console.log(this.context); return ( <div style=> <h1>测试上下文</h1> </div> ) } } // 2. class TestContext extends React.Component { render () { return ( <ThemeCtx.Consumer> { (value) => ( <div style=> <h1>测试上下文</h1> </div> ) } </ThemeCtx.Consumer> ) } }
高阶组件
高阶组件实际上就是一个函数,是一个纯函数(唯一的输入,得到唯一的输出),所以高阶组件也叫做高阶函数
作用:是一种组件业务逻辑复用的高阶技巧
原理:是基于react组件的组合特性而来的一种设计模式
高阶组件为容器,被高阶组件修饰的组件,叫UI组件
当一个UI组件同时被多个高阶组件修饰时,props会丢失,在高阶组件内 使用
<WrappedComponent {...this.props} />
保存上一个被修饰组件的props属性高阶组件的使用
// 高阶组件的定义 import React from 'react'; export default function test (WrappedComponent) { return class extends React.Component { render () { return ( <div> <header>这是官网的菜单</header> <WrappedComponent hehe="hehe" {...this.props} /> <footer>这是底部</footer> </div> ) } } } // 高阶组件的使用 import test from '../hoc/testHoc'; // TestHoc为被修饰的组件 export default test(TestHoc);