【问题标题】:How can I convert a class with a constructor to a functional component using React Hooks?如何使用 React Hooks 将具有构造函数的类转换为功能组件?
【发布时间】: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(() => {});

但我不确定如何处理 toggleVisibilityhandleOnBlur

【问题讨论】:

标签: reactjs constructor react-hooks react-functional-component


【解决方案1】:

您无需在功能组件内使用构造函数(除非遇到一些困难的特定问题)。您可以像这样在功能组件中使用简单的箭头函数:

const App = props => {
    const toggleVisibility = toggleProps => {
        console.log('toggleProps should be true', toggleProps);
    };

    const handleOnBlur = () => {};

    return (
        <>
            <button onClick={handleOnBlur} />
            <button
                onClick={() => {
                    toggleVisibility(true);
                }}
            />
        </>
    );
};

【讨论】:

    【解决方案2】:

    不需要绑定和useConstructor,下面应该是等价的:

    const App = (props) => {
      let toggleVisibility;
      let handleOnBlur;
      // ... rest of your component logic
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-09
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多