**扩充组件。
创建一个函数扩充之后返回另一个函数**
import React, { Component } from 'react'
function bala(props){
return(
<div>
{props.age} - {props.name}
</div>
)
}
function moreStage(Component){
const moreComponent = props =>{
return <Component {...props} name="jack"/>
}
return moreComponent
}
export default moreStage(bala)
App.js中使用
import React from 'react';
import './App.css';
import Hoc from './Hoc'
function App() {
return (
<div className="App">
<Hoc age="12"/>
</div>
);
}
export default App;
链式调用
import React, { Component } from 'react'
function bala(props){
return(
<div>
{props.age} - {props.name}
</div>
)
}
function moreStage(Component){
const moreComponent = props =>{
return <Component {...props} name="jack"/>
}
return moreComponent
}
function withlog(Component){
console.log(Component.name+'加强的')
return props =>{
return <Component {...props} />
}
}
export default moreStage(withlog(moreStage(withlog(bala))))
装饰器写法
npm i @babel/plugin-proposal-decorators -D
在config-overrides.js中添加
const {override,fixBabelImports,addDecoratorsLegacy} = require('customize-cra')
// override返回一个函数 该函数返回对象作为webpack的配置对象
module.exports = override(
fixBabelImports("import",{
libraryName:'antd',
libraryDirectory:'es',
style:'css'
}),
addDecoratorsLegacy()
)
import React, { Component } from 'react'
function withlog(Component){
console.log(Component.name+'加强的')
return props =>{
return <Component {...props} />
}
}
function moreStage(Component){
const moreComponent = props=>{
return <Component {...props} name="jack"/>
}
return moreComponent
}
@withlog
@moreStage
@withlog
class bala extends Component{
render(){
return(
<div>
{this.props.age} - {this.props.name}
</div>
)
}
}
// export default moreStage(withlog(moreStage(withlog(bala))))
export default bala
组件复合
import React, { Component } from 'react'
function Dialog(props){
let color = props.color||'yellow'
return (
<div style={{border:`1px solid ${color}`}}>
{/* children是固定的名称 相当于slot,匿名插槽 */}
{props.children}
{props.foo('子组件传过来的')}
<div>
{/* 具名插槽 */}
{props.footer}
</div>
</div>
)
}
function WelcomeDialog(){
let footer = <button onClick={()=>alert('...')}>确认</button>
return (
//传递任意合法表达式
<Dialog color="lightBlue" footer={footer} foo={(c)=><p>{c}</p>}>
<p>React牛逼</p>
</Dialog>
)
}
export default function Composition(){
return <WelcomeDialog>
}
简易版的redux
import React, { Component } from 'react'
const Context = React.createContext()
const store = {
token:'kkk'
}
export default class ContextText extends Component {
render() {
return (
<Context.Provider value={store}>
<div>
<Context.Consumer>
{store=> <p>{store.token}</p>}
</Context.Consumer>
</div>
</Context.Provider>
)
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。