如何在React中将HTML元素传递给高阶函数(HOC)? [英] How do I pass an HTML element to a higher-order function (HOC) in React?
问题描述
我经常使用 HOC 为现有的React组件提供其他功能,这很简单:
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);
但是,我需要包装一个简单的HTML input
,它不作为独立的React组件存在.我尝试过
However, I need to wrap a simple HTML input
, which doesn't exist as a standalone React component. I tried
const EnhancedInput = higherOrderComponent(<input />);
,并出现以下错误:
Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
如何正确传递输入?
推荐答案
传递要包装的HTML元素的字符串名称:
Pass the string name of the HTML element you want to wrap:
const EnhancedInput = higherOrderComponent('input');
该错误将我引导到需要执行的操作中,并且在分解JSX正在执行的操作时更有意义. <input />
只是React.createElement('input')
的 JSX语法糖
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')
.
如果HOC看起来像这样:
If the HOC looks something like this:
const higherOrderComponent = (Component) => {
return class extends React.Component {
render() {
return (
<Component {...} />
);
}
}
};
然后render
方法最终将返回
React.createElement(Component, {...});
因此,将字符串'input'
传递到HOC意味着它将返回React.createElement('input', {...});
,与上面声明的<input />
相同.
Therefore, passing the string 'input'
to the HOC means it will return React.createElement('input', {...});
, which is the same as <input />
as asserted above.
这篇关于如何在React中将HTML元素传递给高阶函数(HOC)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!