React基础之高阶组件-爱代码爱编程
1、高阶组件其实就是函数,它接收组件作为参数,对组件进行增强后返回
const Hoc = Component => EnhancedComponet
2、举例:如果要为每个组件添加相同的className。可以编写一个高阶组件
const withClassName = Component => props => (<Component {...props} className="my-class"/>)
3、举例:为每个组件添加事件监听window的窗口宽度变化,可以编写一个高阶组件,withInnerWidth 函数的入参Component 是需要被增强的原始组件,withInnerWidth 函数的返回值,是增强后的组件,能实时监听window宽度变化,并将宽度以props的形式传给Component
import React from 'react';
export const withInnerWidth = Component => (
class extends React.Component {
constructor(props) {
super(props);
this.state = {
innerWidth: window.innerWidth
}
}
componentDidMount() {
window.addEventListener('resize', this.handleResize)
}
handleResize = () => {
this.setState({
innerWidth: window.innerWidth
})
}
render() {
return <Component {...this.props} {...this.state}/>
}
}
)
// Button.jsx:待增强组件
import React from 'react';
import PropTypes from 'prop-types';
export default function Button({text, user, innerWidth}){
return (
<div>
<div>{user.name}</div>
<div>{user.subName}</div>
<div>{user.age}</div>
<div>窗口宽度为:{innerWidth}</div>
<button>{text}</button>
</div>
)
}
Button.propTypes = {
text: PropTypes.string,
/**
* 用户对象
*/
user: PropTypes.shape({
/**
* 用户名称
*/
name: PropTypes.string.isRequired,
subName: PropTypes.string
}).isRequired
}
import React from 'react';
import ReactDOM from 'react-dom';
import Button from "./Components/ReactTest/Button";
import {withInnerWidth} from "./Components/ReactTest/EnhancedComponent"
// 获取增强函数
const WithButton = withInnerWidth(Button)
ReactDOM.render(<WithButton text={'提交'} user={{name:'张三', subName:'李四', age:100}}/>, document.getElementById('root'));
4、高阶组件的好处:
(1)首先没有污染任何状态
(2)其次不需要组件来实现任何方法,组件和高阶组件没有耦合,可以在整个应用中复用它们
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 本文链接: https://blog.csdn.net/zhujian82637/article/details/111088520