React:Hooks 会取代 HOC 和渲染道具吗?

从React Hooks FAQ 中,我们了解到钩子可以替代返回/渲染单个组件的 HOC 和渲染道具。

我试图更好地理解这一点,以及为什么这是事实。

我们先来看看 HOC:

HOC 是一个函数,它将一个组件作为参数,将它包装在周围的逻辑中,如效果和状态,并返回一个新组件。自定义钩子究竟如何取代它?我们仍然需要用其他逻辑包装输入函数的函数。

查看渲染道具:

渲染道具是我们作为道具传递给另一个组件的组件,然后使用一些新的道具渲染传递的组件。我想我们可以通过创建一个返回完整组件的自定义钩子来替换它,然后在任何需要的组件中使用该钩子。因此,父级不必将组件作为道具传递给它的子级。这就是钩子会取代渲染道具的方式吗?

对钩子如何在最常见的用例中替换 HOC 和渲染道具的解释,最好是代码示例,将不胜感激。


手掌心
浏览 165回答 1
1回答

叮当猫咪

HOC 和渲染道具有很多不同的用途,所以我不可能将它们全部都涵盖在内,但基本上该段落指出,您使用 HOC/渲染道具的许多情况也可以通过钩子实现。这不会使 HOCs/render props 过时,但钩子是另一个可供您在组件之间共享代码的工具。HOC/render prop 的一项常见工作是管理一些数据的生命周期,并将该数据传递给派生组件或子组件。在以下示例中,目标是获取窗口宽度,包括与之相关的状态管理和事件侦听。HOC 版本:function withWindowWidth(BaseComponent) {&nbsp; class DerivedClass extends React.Component {&nbsp; &nbsp; state = {&nbsp; &nbsp; &nbsp; windowWidth: window.innerWidth,&nbsp; &nbsp; }&nbsp; &nbsp; onResize = () => {&nbsp; &nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; &nbsp; windowWidth: window.innerWidth,&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; }&nbsp; &nbsp; componentDidMount() {&nbsp; &nbsp; &nbsp; window.addEventListener('resize', this.onResize)&nbsp; &nbsp; }&nbsp; &nbsp; componentWillUnmount() {&nbsp; &nbsp; &nbsp; window.removeEventListener('resize', this.onResize);&nbsp; &nbsp; }&nbsp; &nbsp; render() {&nbsp; &nbsp; &nbsp; return <BaseComponent {...this.props} {...this.state}/>&nbsp; &nbsp; }&nbsp; }&nbsp; // Extra bits like hoisting statics omitted for brevity&nbsp; return DerivedClass;}// To be used like this in some other file:const MyComponent = (props) => {&nbsp; return <div>Window width is: {props.windowWidth}</div>};export default withWindowWidth(MyComponent);渲染道具版本:class WindowWidth extends React.Component {&nbsp; propTypes = {&nbsp; &nbsp; children: PropTypes.func.isRequired&nbsp; }&nbsp; state = {&nbsp; &nbsp; windowWidth: window.innerWidth,&nbsp; }&nbsp; onResize = () => {&nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; windowWidth: window.innerWidth,&nbsp; &nbsp; })&nbsp; }&nbsp; componentDidMount() {&nbsp; &nbsp; window.addEventListener('resize', this.onResize)&nbsp; }&nbsp; componentWillUnmount() {&nbsp; &nbsp; window.removeEventListener('resize', this.onResize);&nbsp; }&nbsp; render() {&nbsp; &nbsp; return this.props.children(this.state.windowWidth);&nbsp; }}// To be used like this:const MyComponent = () => {&nbsp; return (&nbsp; &nbsp; <WindowWidth>&nbsp; &nbsp; &nbsp; {width => <div>Window width is: {width}</div>}&nbsp; &nbsp; </WindowWidth>&nbsp; )}最后但并非最不重要的是,钩子版本const useWindowWidth = () => {&nbsp; const [width, setWidth] = useState(window.innerWidth);&nbsp; useEffect(() => {&nbsp; &nbsp; const onResize = () => setWidth(window.innerWidth);&nbsp; &nbsp; window.addEventListener('resize', onResize);&nbsp; &nbsp; return () => window.removeEventListener('resize', onResize);&nbsp; }, [])&nbsp; return width;}// To be used like this:const MyComponent = () => {&nbsp; const width = useWindowWidth();&nbsp; return <div>Window width is: {width}</div>;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript