高阶组件/Higher-Order Components
Higher-Order Components就是一个函数,传给它一个组件,它返回一个新的组件。
1. 进行某些方法或是属性的复用
2. 让外层的组件替我们完成任务,那么里层组件直接使用就可以了
举个简单的例子
import React from 'react'
import A from './components/A'
export const HocComp = comp => {
return class newcomp extends React.Component {
xx = () => {//表示某个公用的方法
}
render(){
return ( //生成一个新的组件 这个组件包含公用的方法
<A/ xx = { this.xx }>
)
}
}
}
使用是就调用这个方法 传入组件做参数 生成新的组件并赋值就好了
实现react动画
1.安装 react-transition-group yarn add react-transition-group
2.安装 animate.css yarn add animate.css
3.在组件上方引入 import { CSSTransition } from 'react-transition-group' 将需要动画的标签放入 CSSTransition这标签内
组件内部
import React,{ Component, Fragment } from 'react'
import { AnimateHoc } from '../../hoc'
import Content from './content'
const HocCont = AnimateHoc(Content)
class AnimateComp extends Component{
constructor( props ){
super( props )
this.state = {
flag:true
}
}
changeFlag = () => {
const {flag} = this.state
this.setState({
flag:!flag
})
}
render(){
const { flag } =this.state
return (
<Fragment>
<button onClick = { this.changeFlag }>切换</button>
<HocCont flag = { flag }></HocCont>
</Fragment>
)
}
}
export default AnimateComp
---------------------------------------------------------------------------
hoc封装
import React from 'react'
import {CSSTransition} from 'react-transition-group'
import 'animate.css'
export const AnimateHoc = Comp => {
return class withAnimate extends React.Component {
render(){
const { flag } = this.props
return (
<CSSTransition
in = { flag }
timeout = { 2000 }
unmountOnExit
classNames = { {
enter: 'animated',
enterActive: 'slideInLeft',
exit: 'animated',
exitActive: 'bounceOut',
} }
>
<Comp/>
</CSSTransition>
)
}
}
}