如何使用 React Hooks 将带有构造函数的 class 转换为功能组件?
How can I convert a class with a constructor to a functional component using React Hooks?
如何使用 React Hooks 将带有构造函数的以下 class 转换为功能组件?
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);
}
然后将 class 更改为函数并像这样使用它:
const App = () => {
useConstructor(() => {});
但我不确定如何处理 toggleVisibility
和 handleOnBlur
不需要绑定和useConstructor,下面应该是等价的:
const App = (props) => {
let toggleVisibility;
let handleOnBlur;
// ... rest of your component logic
}
您无需在功能组件内部使用构造函数(除非遇到一些棘手的特定问题)。你可以像函数组件中的简单箭头函数那样做:
const App = props => {
const toggleVisibility = toggleProps => {
console.log('toggleProps should be true', toggleProps);
};
const handleOnBlur = () => {};
return (
<>
<button onClick={handleOnBlur} />
<button
onClick={() => {
toggleVisibility(true);
}}
/>
</>
);
};
如何使用 React Hooks 将带有构造函数的以下 class 转换为功能组件?
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);
}
然后将 class 更改为函数并像这样使用它:
const App = () => {
useConstructor(() => {});
但我不确定如何处理 toggleVisibility
和 handleOnBlur
不需要绑定和useConstructor,下面应该是等价的:
const App = (props) => {
let toggleVisibility;
let handleOnBlur;
// ... rest of your component logic
}
您无需在功能组件内部使用构造函数(除非遇到一些棘手的特定问题)。你可以像函数组件中的简单箭头函数那样做:
const App = props => {
const toggleVisibility = toggleProps => {
console.log('toggleProps should be true', toggleProps);
};
const handleOnBlur = () => {};
return (
<>
<button onClick={handleOnBlur} />
<button
onClick={() => {
toggleVisibility(true);
}}
/>
</>
);
};