简体   繁体   English

如何在类中编写handleClick而不是在react js中导出默认函数

[英]How to write handleClick in class Instead of export default function in react js

I'm new In react and I want to use material UI in my project, I read the doc of the menu part like this , but I can't write my code, my problem is how to convert the export default function to class PageHeader extends React.Component{} for this part我是新的反应,我想在我的项目中使用材质 UI,我像这样阅读了菜单部分的文档,但我无法编写代码,我的问题是如何将export default function转换为class PageHeader extends React.Component{}为这部分class PageHeader extends React.Component{}

    const ITEM_HEIGHT = 100;
    const [anchorEl, setAnchorEl] = React.useState(null);
    const open = Boolean(anchorEl);
    const handleClick = (event) => {
        setAnchorEl(event.currentTarget);
    };
    const handleClose = () => {
        setAnchorEl(null);
    };

The example you linked uses function components.您链接的示例使用了函数组件。 We can convert these to more traditional class components like what you want, or you can use the function as a component - the example is able to use <LongMenu /> because it is a component, just declared using a function instead of a class.我们可以将这些转换为您想要的更传统的类组件,或者您可以将函数用作组件 - 该示例能够使用<LongMenu />因为它是一个组件,只是使用函数而不是类声明。 There is information about converting a function component to a class in the React docs . React 文档中有关于将函数组件转换为类的信息

Some of the key points when using a class instead of a function is hooks like useState and useEffect don't really exist in a class.使用类而不是函数时的一些关键点是像useStateuseEffect这样的钩子useEffect并不存在于类中。 Instead, we store the state as a field in the class, and use lifecycle methods .相反,我们将状态存储为类中的一个字段,并使用生命周期方法 A class for the snippet you provided could look like:您提供的代码段的类可能如下所示:

class PageHeader extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      anchorEl: null
    };
  }

  handleClick = event => {
    this.setState({ anchorEl: event.currentTarget });
  }

  handleClose = () => {
    this.setState({ anchorEl: null });
  }

  render() {
    return (...);
  }
}

export default PageHeader;

Instead of using the useState hook, we can store the state of anchorEl in this.state , and update it with this.setState .而不是使用的useState挂钩,我们可以存储的状态anchorElthis.state ,并与更新this.setState

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM