【问题标题】:Unexpected Snackbar+Alert behavior意外的 Snackbar+Alert 行为
【发布时间】:2022-01-23 09:39:57
【问题描述】:

为什么会报错:

import Snackbar from "@mui/material/Snackbar";
import MuiAlert from "@mui/material/Alert";
const Alert = ({children}) => <MuiAlert>{children}</MuiAlert>

<Snackbar open>
    <Alert>test</Alert>
</Snackbar>

(但这不是?)

import Snackbar from "@mui/material/Snackbar";
import MuiAlert from "@mui/material/Alert";

<Snackbar open>
    <MuiAlert>test</MuiAlert>
</Snackbar>

据我了解,它们的工作原理应该相同。

【问题讨论】:

    标签: javascript node.js reactjs material-ui


    【解决方案1】:

    当您使用单行组件语法时,您不需要使用return 关键字来获取组件。 =&gt; 就够了:

    import Snackbar from "@mui/material/Snackbar";
    import MuiAlert from "@mui/material/Alert";
    const Alert = ({children}) => <MuiAlert>{children}</MuiAlert>
    
    export default function App() {
      return (
        <>
          <Snackbar open>
            <Alert>test</Alert>
          </Snackbar>
        </>
      );
    }
    

    【讨论】:

      【解决方案2】:

      事实证明我需要使用React.forwardRef 将ref 传递给警报:

      import Snackbar from "@mui/material/Snackbar";
      import MuiAlert from "@mui/material/Alert";
      const Alert = React.forwardRef(({children}, ref) => <MuiAlert ref={ref}>{children}</MuiAlert>)
      
      <Snackbar open>
          <Alert>test</Alert>
      </Snackbar>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-04
        • 2016-07-16
        • 2016-05-10
        • 2020-07-23
        • 2021-08-23
        • 2021-11-16
        • 2017-10-20
        • 2016-06-29
        相关资源
        最近更新 更多