简体   繁体   中英

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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