【问题标题】:How to wrap a function which contains hooks with HoC如何用 HoC 包装包含钩子的函数
【发布时间】:2020-02-06 10:32:18
【问题描述】:

正如标题所示,我希望能够在 HoC 中包装一个函数(其中包含)钩子。

在下面的示例中,我希望能够使用 div 元素标记从 TestView 包装 JSX,其中 className="someClassName"。但是我得到以下异常:

Hooks 只能在函数组件的主体内部调用。 这可能由于以下原因之一而发生: 1. React 和渲染器的版本可能不匹配(例如 React DOM) 2. 你可能违反了 Hooks 的规则 3. 你可能在同一个应用程序中拥有多个 React 副本 有关如何调试和 解决这个问题

import React, { Component } from 'react'

function wrap(component) {
    let calledComponent = component()
    return (
        <div className="someClassName">
          {calledComponent}
        </div>
    );
  }


function TestView() {
    const [ val, setValue] = React.useState('Initial Value');
    return (
        <div>
            <input type="text" value={val} onChange={event=>setValue(event.target.value)}/>
        </div>
    )

 }

 export default wrap(TestView);

【问题讨论】:

    标签: reactjs react-hooks react-hoc


    【解决方案1】:

    具体来说,高阶组件是一个函数,它接受一个 组件并返回一个新组件。 react docs

    所以,你必须有一个返回组件的函数,可能是这样的。

    import React, { useState } from 'react';
    import '../styles.css';
    
    const withStyle = WrappedComponent => {
      return function WithStyle() {
        return (
          <div className='myClassStyle'>
            <WrappedComponent />
          </div>
        );
      };
    };
    
    function TestView() {
      const [val, setVal] = useState('Initial Value');
      return (
        <div>
          <input type='text' value={val} onChange={e => setVal(e.target.value)} />
        </div>
      );
    }
    
    export default withStyle(TestView);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-29
      • 1970-01-01
      • 2019-10-14
      • 1970-01-01
      • 2021-11-25
      • 2020-07-04
      相关资源
      最近更新 更多