简体   繁体   English

将类组件反应为功能组件

[英]React class component to functional component

I am trying to convert my class component to a functional component, but I'm a little bit confused on how to do it correctly with the toggleMenu.我正在尝试将我的类组件转换为功能组件,但我对如何使用 toggleMenu 正确执行此操作感到有些困惑。 I'm trying to get more familiar with working with just functional components.我正在尝试更加熟悉仅使用功能组件的工作。

The class component is built as:类组件构建为:

class FilterMobile extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      opened: false,
      closed: true,
    };
    this.toggleMenu = this.toggleMenu.bind(this);
  }

  toggleMenu() {
    const { opened } = this.state;
    this.setState({
      opened: !opened,
      closed: opened,
    });
  }

  render() {
    const { opened } = this.state;

    return (
      <>
        <div>
          <Button onClick={this.toggleMenu} className="full-width filter-dropdown-button">
            <div>
              <span className="bold">Filters</span>
            </div>

            {this.state.opened && <div className="icon tmm-exit" />}
            {this.state.closed && <div className="icon tmm-filter" />}
          </Button>

          <Button className="full-width button-clear-filter">
            Clear <div className="icon tmm-exit" />
          </Button>
        </div>

        {opened && (

          <CollapseContainer>
            <CategoriesCollapseContainer>
              <Collapse
                accordion={true}
                expandIcon={expandIcon}
                className="mobile-collapse"
              >
                {this.props.children}
              </Collapse>
            </CategoriesCollapseContainer>
          </CollapseContainer>
        )}
      </>
    );
  }
}

Any help would be really appreciated.任何帮助将非常感激。

You should use just one variable in the state "opened" and then compute the "closed" value;您应该在“打开”状态下只使用一个变量,然后计算“关闭”值; Also I encourage to use React hooks.我也鼓励使用 React 钩子。

function FilterMobile() {
  const [opened, setOpen] = React.useState(false);
  const closed = !opened;
  const toggleMenu = () => setOpen(isOpened => !isOpened);

  return (
    <>
      {/* Use it as you want */}
    </>
  );
}

代替状态变量,您需要使用反应钩子https://reactjs.org/docs/hooks-intro.html

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

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