求助:如何将带toggleMenu的React类组件转为函数组件
Hey there! Let's walk through converting your class component to a functional one—this will help you get up to speed with React hooks, the standard for modern functional component development.
First, let's break down what your original component does: it manages an open/closed state for a menu, toggles that state when the button is clicked, and shows/hides content based on the state. We can simplify this a bit in the functional version by cutting redundant state (you don't need both opened and closed—closed is just the opposite of opened!).
Here's the converted functional component:
import React, { useState } from 'react'; const FilterMobile = (props) => { // Initialize state with useState: we only need `opened` since `closed` is !opened const [opened, setOpened] = useState(false); // Toggle function: no need to bind `this` in functional components const toggleMenu = () => { setOpened(prevOpened => !prevOpened); }; return ( <> <div> <Button onClick={toggleMenu} className="full-width filter-dropdown-button"> <div> <span className="bold">Filters</span> </div> {/* Use !opened instead of a separate `closed` state */} {opened && <div className="icon tmm-exit" />} {!opened && <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" > {props.children} </Collapse> </CategoriesCollapseContainer> </CollapseContainer> )} </> ); };
Key changes explained:
- State management with
useState: We replaced the class constructor's state with theuseStatehook. Instead of tracking bothopenedandclosed, we only trackopened—closedis just!opened, which eliminates redundant state and keeps logic simpler. - No
thisbinding: In functional components, we don't need to bind methods tothisbecause there's no class instance to reference. ThetoggleMenufunction is a regular function that directly updates state usingsetOpened. - Safe state updates: When toggling, we use the functional update form (
prevOpened => !prevOpened)—this is a best practice when the new state depends on the previous state, ensuring we always work with the latest state value. - Cleaner JSX: We removed all references to
this.stateandthis.props, replacing them with the directly accessibleopenedvariable andpropsobject (you could also destructurepropslikeconst { children } = propsat the top if you prefer a more concise style).
This version does exactly the same thing as your original class component, but it's more concise and follows modern React practices. Let me know if you have any questions about hooks or functional component patterns!
内容的提问来源于stack exchange,提问作者kb_

