HOC函数将父级属性乡下传递,并追加新属性,为Dumb添加样式和newNamevue
// App.js
import React from 'react';
import Dumb from './HocDemo';
function App() {
return (
<div className="App">
<Dumb name="木偶组件" color="#afa"/>
</div>
);
}
export default App;
// HocDemo.js
import React from 'react'
// 传入一个组件返回一个函数式组件
const HOC = (Comp) => (props) => {
const style = {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
width: '500px',
height: '300px',
border: `2px solid ${props.color}`,
}
return <Comp style={style} {...props} newName="高阶组件" />
}
// 木偶组件
function Dumb(props) {
return (
<div style={props.style}>
我是{props.newName || props.name} || 本体是{props.name}
</div>
)
}
export default HOC(Dumb);
复制代码
一样还能够为Dumb增长生命周期等,以便处理逻辑react
// 修改HOC函数 在函数内部定义一个组件 最后将组件返回
const HOC = (Comp) => {
class NewDumb extends React.Component {
componentDidMount() {
console.log('NewDumb')
}
render() {
const style = {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
width: '500px',
height: '300px',
border: `2px solid ${this.props.color}`,
}
return <Comp style={style} {...this.props} newName="高阶组件" />
}
}
return NewDumb
}
复制代码
首先须要几个包bash
yarn add react-app-rewired customize-cra @babel/plugin-proposal-decorators -D
复制代码
跟目录新建config-overrides.js (至关于vue.config.js) 内容以下babel
const { override, addDecoratorsLegacy } = require('customize-cra');
module.exports = override(
addDecoratorsLegacy(),
);
复制代码
修改HocDemo.jsapp
//其余部分不变 其中装饰器必须使用class声明组件
@HOC
class Dumb extends React.Component{
render(){
const { style, newName, name } = this.props
return (
<div style={style}>
我是{newName || name} || 本体是{name}
</div>
)
}
}
export default Dumb;
复制代码
写一个Context.js 在App.js中使用, 声明一个上下文和初始化数据store, 封装两个函数withConsumer、withProvider 经过装饰器使父级组件具备提供者功能 则Container组件下 被withConsumer包裹过的组件都有消费者功能 实现跨层级组件通讯 父=>孙ide
import React, { Component } from "react";
// 生成一个上下文
const Context = React.createContext();
const store = {
name: "Zzz",
};
// 为Provider封装一个高阶组件
const withProvider = Comp => props => (
<Context.Provider value={store}>
<Comp {...props} />
</Context.Provider>
);
// 为Consumer封装一个高阶组件
const withConsumer = Comp => props => (
<Context.Consumer>
{value => <Comp {...props} value={value} />}
</Context.Consumer>
);
//使孙子组件足有消费能力
@withConsumer
class Grandson extends Component {
render() {
return <div>{this.props.value.name}</div>;
}
}
//是父组件具备提供能力
@withProvider
class Provider extends Component {
render() {
return <div><Container/></div>;
}
}
// 一个容器组件
function Container(props) {
return (
<div> <Container2/> <Container3/> </div>
)
}
// 一个容器组件2
function Container2(props) {
return (
<div> <Grandson/> </div>
)
}
// 一个容器组件3
function Container3(props) {
return (
<div> Container3 </div>
)
}
export default Provider
复制代码