How do I pass an HTML element to a higher-order function (HOC) in React?

丶灬走出姿态 提交于 2019-12-08 19:39:45

问题


I often use HOCs to provide additional functionality to an existing React component, which is pretty straightforward:

import Component from '/path/to/Component';
import higherOrderComponent from '/path/to/higherOrderComponent';

const EnhancedComponent = higherOrderComponent(Component);

However, I need to wrap a simple HTML input, which doesn't exist as a standalone React component. I tried

const EnhancedInput = higherOrderComponent(<input />);

and got the following error:

Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

How can I properly pass the input?


回答1:


Pass the string name of the HTML element you want to wrap:

const EnhancedInput = higherOrderComponent('input');

The error clued me into what I needed to do and made more sense when breaking down what JSX is doing. <input /> is simply JSX syntactic sugar for React.createElement('input').

If the HOC looks something like this:

const higherOrderComponent = (Component) => {
  return class extends React.Component {
    render() {
      return (
        <Component {...} />
      );
    }
  }
};

then the render method is ultimately returning

React.createElement(Component, {...});

Therefore, passing the string 'input' to the HOC means it will return React.createElement('input', {...});, which is the same as <input /> as asserted above.




回答2:


Another solution is to use a function that returns the HTML you want.

const EnhancedComponent = higherOrderComponent(()=><input />)



来源:https://stackoverflow.com/questions/48847684/how-do-i-pass-an-html-element-to-a-higher-order-function-hoc-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!