ITMISS
2023-08-18 16:26:57
基于布爾狀態(tài)更改,我嘗試更改組件的樣式,但由于某種原因,它僅在頁(yè)面刷新后顯示更改。在我的父應(yīng)用程序組件中,我執(zhí)行以下操作:import React from "react";import Layout from "./Layout";export default function App() { const [loading, setLoading] = React.useState(true); React.useEffect(() => { setTimeout(() => { setLoading(!loading); }, 2000); }, [loading]); return <Layout loading={loading} />;}我的Layout組件捕獲這個(gè)loading變量并將其發(fā)送到makeStyles鉤子,import React from "react";import { makeStyles } from "@material-ui/core";const useStyles = makeStyles((theme) => ({ root: {}, wrapper: ({ loading }) => ({ paddingTop: 64, [theme.breakpoints.down("lg")]: { paddingLeft: loading ? 0 : 100 } })}));const Layout = React.memo(({ loading }) => { const classes = useStyles({ loading }); return ( <div className={classes.root}> <div>side</div> <div className={classes.wrapper}> is loading: {JSON.stringify(loading)} </div> </div> );});export default Layout;執(zhí)行console.log后wrapper: ({ loading }) => ({打印正確的值loading,但樣式?jīng)]有改變。這里發(fā)生了什么?
1 回答

GCT1015
TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超4個(gè)贊
您的代碼中有兩個(gè)問題,第一個(gè)問題是您使用對(duì)象解構(gòu)兩次:而不是
const Layout = React.memo(({ loading }) => { const classes = useStyles({ loading });
你應(yīng)該 :
const Layout = React.memo(({ loading }) => { const classes = useStyles(loading );
因?yàn)樵诘谝患?jí)中您可以訪問屬性加載,第二個(gè)問題是您在錯(cuò)誤的位置調(diào)用參數(shù),您必須直接在 css 屬性中調(diào)用加載,如下所示:
paddingLeft: (loading) => (loading ? 0 : 100)
這是兩個(gè)更正的鏈接,希望您所期待的 https://codesandbox.io/s/goofy-microservice-y2gql?fontsize=14&hidenavigation=1&theme=dark
添加回答
舉報(bào)
0/150
提交
取消