【问题标题】:Enhance react component with HOC使用 HOC 增强反应组件
【发布时间】:2021-05-25 06:55:49
【问题描述】:

我需要创建一个可重用的相机组件,为此我想传递一个自定义记录按钮,我需要为其附加额外的功能或覆盖按钮文本。

这里是一个例子:

https://codesandbox.io/s/react-hoc-ksjbf

我创建了一个 hoc.js,它采用自定义组件并尝试覆盖 text prop,但出现此错误:

元素类型无效:应为字符串(用于内置组件) 或类/函数(用于复合组件)但得到:对象。

我不明白这是错的,有什么想法吗?

【问题讨论】:

    标签: reactjs components high-order-component


    【解决方案1】:

    问题

    您将 JSX 文字(即对象)作为 prop 值传递给(传递给)高阶组件与 React 组件。

    recordbutton={<Button text="Original Text" />}
    

    解决方案

    改为传递一个 React 组件

    <Camera recordbutton={(props) => <Button text="Original Text" {...props} />} />
    

    或定义并通过

    const RecordButton = (props) => <Button text="Original Text" {...props} />;
    
    export default function App() {
      return (
        <div className="App">
          <Camera recordbutton={RecordButton} />
        </div>
      );
    }
    

    或者直接传递Button组件

    export default function App() {
      return (
        <div className="App">
          <Camera recordbutton={Button} />
        </div>
      );
    }
    

    只要您将所有道具传递给组件,那么 HOC 就可以注入/覆盖道具值。

    更新 HOC 以在 提供覆盖之前传播传递的道具,这样 HOC 可以实际上覆盖它们。

    function alterText(Component) {
      return function (props) {
        return <Component {...props} text="new text"  />;
      };
    }
    

    【讨论】:

      猜你喜欢
      • 2018-09-06
      • 2021-04-18
      • 2021-05-11
      • 2019-08-12
      • 1970-01-01
      • 2018-09-11
      • 1970-01-01
      • 2017-09-02
      • 2022-07-13
      相关资源
      最近更新 更多