react function HOC(高阶组件)实现和使用
function myHOC(propsHandler) {
return function (WrappedComponent) {
return function (props) {
const [newProps] = useState(isFunction(propsHandler) ? propsHandler(props) : props);
const [counter] = useState(100)
console.log('newProps', newProps)
return <WrappedComponent {...newProps} counter={counter} />;
};
};
}
function YourComponent(props) {
const { counter } = props
const [count, setCount] = useState(0)
return <div>
<button onClick={() => setCount((c) => c + 1)}>加一</button>
<p>自身定义的count:{count}</p>
<p>高阶组件定义的counter:{counter}</p>
</div>
}
export default myHOC((props)=>({...props}))(YourComponent)