问题
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