猿问

React Hooks 问题:打开一个模块化的模态

我正在为学校项目开发基于Material UI的React.js应用程序。我的项目基于Material UI 文档中的React + Material UI + Firebase示例。目前,我正在尝试使用,这样我就可以避免使用 Redux(并在将来开发的东西上做得更好)。在 app 组件中,它们有一个openDialog函数,该函数作为一种基于 dialogId 打开模态的方式。React Hooks


class App extends Component {

  constructor(props) {

    super(props);


this.state = {

  signUpDialog: {

    open: false

  },


  signInDialog: {

    open: false

  },


  settingsDialog: {

    open: false

  },


  signOutDialog: {

    open: false

  }

};

}


// CURRENT, NON-HOOKS WAY

openDialog = (dialogId, callback) => {

   const dialog = this.state[dialogId];


   if (!dialog || dialog.open === undefined || null) {

     return;

   }

   dialog.open = true;


   this.setState({ dialog }, callback);

 };

然后他们有一个导航栏,而不是使用相应的对话框调用此函数(例如onSignUpClick={() => this.openDialog('signUpDialog')})我目前正在尝试使用钩子将其移动


有人可以教我/帮我转换这个模块化功能吗!


互换的青春
浏览 160回答 2
2回答

翻翻过去那场雪

import React from 'react'function App({ callback }) {&nbsp; // if we just mind about the active dialog,&nbsp; // we don't need to save the state of the others&nbsp; const [dialog, setDialog] = React.useState(null)&nbsp; // here useEffect is called every time, dialog changed,&nbsp; // we also need to put `callback` in the array otherwise&nbsp; // React throw a warning.&nbsp; // React.useEffect act like `ComponentDidMount`, so we better&nbsp; // check dialog is not empty otherwise it will call our callback&nbsp; // straight away AFTER the render and that's not what we want&nbsp; React.useEffect(() => {&nbsp; &nbsp; if (dialog) callback()&nbsp; }, [dialog, callback])&nbsp; // You said we were in a navBar so i can assume you can do&nbsp;&nbsp; // something like this&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; {['signUp', 'signInDialog', 'settingsDialog', 'signOutDialog'].map(&nbsp; &nbsp; &nbsp; &nbsp; elem => (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div key={elem} onClick={() => setDialog({ [elem]: true })}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {elem}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; ),&nbsp; &nbsp; &nbsp; )}&nbsp; &nbsp; </div>&nbsp; )}export default App

狐的传说

const [dialog, setDialog] = useState({&nbsp; isOpensignUp: false,&nbsp; isOpenSignIn: false,&nbsp; isOpenSignOut: false,&nbsp; isOpenSetting: false});const handleDialog =&nbsp; e&nbsp; => {&nbsp; setDialog({...dialog,[e.target.name]:true});}<button name= "isOpensignUp" onClick={handleDialog} /><Dialog open={dialog.isOpensignUp}>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答