将类组件反应为功能组件

时间:2020-09-09 15:07:24

标签: javascript reactjs

我正在尝试将我的类组件转换为功能组件,但是对于如何使用toggleMenu正确地进行操作,我有些困惑。我试图使人们更熟悉仅使用功能组件。

类组件的构建方式为:

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>
        )}
      </>
    );
  }
}

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

您应该仅在“打开”状态下使用一个变量,然后计算“关闭”值; 另外,我鼓励使用React钩子。

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

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

答案 1 :(得分:-1)

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