如何用 HoC 包装一个包含钩子的函数
How to wrap a function which contains hooks with HoC
如标题所示,我希望能够在 HoC 中包装一个函数(包含)挂钩。
在下面的示例中,我希望能够使用 div
元素标记(其中 className="someClassName"
包装来自 TestView
的 JSX。但是我得到以下异常:
Hooks can only be called inside of the body of a function component.
This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app See for tips about how to debug and
fix this
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);
Concretely, a higher-order component is a function that takes a
component and returns a new component.
react docs
所以,你必须有一个 returns 组件的功能,可能像这样。
import React, { useState } from 'react';
import '../styles.css';
const withStyle = WrappedComponent => {
return function WithStyle() {
return (
<div className='myClassStyle'>
<WrappedComponent />
</div>
);
};
};
function TestView() {
const [val, setVal] = useState('Initial Value');
return (
<div>
<input type='text' value={val} onChange={e => setVal(e.target.value)} />
</div>
);
}
export default withStyle(TestView);
如标题所示,我希望能够在 HoC 中包装一个函数(包含)挂钩。
在下面的示例中,我希望能够使用 div
元素标记(其中 className="someClassName"
包装来自 TestView
的 JSX。但是我得到以下异常:
Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app See for tips about how to debug and fix this
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);
Concretely, a higher-order component is a function that takes a component and returns a new component. react docs
所以,你必须有一个 returns 组件的功能,可能像这样。
import React, { useState } from 'react';
import '../styles.css';
const withStyle = WrappedComponent => {
return function WithStyle() {
return (
<div className='myClassStyle'>
<WrappedComponent />
</div>
);
};
};
function TestView() {
const [val, setVal] = useState('Initial Value');
return (
<div>
<input type='text' value={val} onChange={e => setVal(e.target.value)} />
</div>
);
}
export default withStyle(TestView);