【发布时间】: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