【发布时间】:2021-07-04 04:15:19
【问题描述】:
如何使用 React Hooks 将以下带有构造函数的类转换为功能组件?
class App extends React.Component {
constructor(props) {
super(props);
this.toggleVisibility = this.toggleVisibility.bind(this);
this.handleOnBlur = this.handleOnBlur.bind(this);
}
我在网上看到你可以为构造函数做这样的事情:
const useConstructor(callBack = () => {}) {
const [hasBeenCalled, setHasBeenCalled] = useState(false);
if (hasBeenCalled) return;
callBack();
setHasBeenCalled(true);
}
然后把类改成函数,这样使用:
const App = () => {
useConstructor(() => {});
但我不确定如何处理 toggleVisibility 和 handleOnBlur
【问题讨论】:
-
您正在做的
binds 是对使用functional components时不存在的问题的修复,因此使useConstructor挂钩无用。参考stackoverflow.com/questions/53215067/…
标签: reactjs constructor react-hooks react-functional-component