将类转换为函数:传递状态对象



我目前正在使用学校项目的Material UI文档中的React + Material UI + Firebase模板。现在,我正在尝试将 App.js 转换为使用钩子。到目前为止,我有这个,但我需要 DialogHost 组件的帮助,我们在其中传递各种对话框。这是文件的简化版本

import React, { useState } from 'react';
import { ThemeProvider } from '@material-ui/core/styles';
import Navbar from './components/Navbar'
import DialogHost from './components/DialogHost';
function App() {
const [signedIn, setSignedIn] = useState(false)
const [ready, setReady] = useState(false)
const [dialog, setDialog] = useState({
isOpenSignUp: false,
isOpenSignIn: false,
isOpenSignOut: false,
isOpenSetting: false
});
const handleOpenDialog =  e  => {
setDialog({...dialog,[e.target.name]: true});
}
const handleCloseDialog =  e  => {
setDialog({...dialog,[e.target.name]: false});
}
return (
<ThemeProvider theme={theme}>
{ready &&
<>
<Navbar 
signedIn={signedIn}
onOpenDialog={handleOpenDialog}
onCloseDialog={handleCloseDialog}
/> 
<DialogHost 
signedIn={signedIn}
// HOW TO CONVERT THESE DIALOGS (which is currently setting state  as signUpDialog: {open: true}) USING HOOKS?
dialogs={
{
signUpDialog: {
dialogProps: {
open: signUpDialog.open,
onClose: (callback) => {
this.closeDialog('signUpDialog');
if (callback && typeof callback === 'function') {
callback();
}
}
}
},
signInDialog: {
dialogProps: {
open: signInDialog.open,
onClose: (callback) => {
this.closeDialog('signInDialog');
if (callback && typeof callback === 'function') {
callback();
}
}
}
},
}
}
/>
</>
}
</ThemeProvider>

);
}
export default App;

如果我没记错的话,我认为上下文 api 可以在这里工作,但只是想知道当前的实现。谢谢!

这将适用于上面的代码:

<DialogHost
signedIn={signedIn}
dialogs={{
signUpDialog: {
dialogProps: {
open: dialog.isOpenSignUp,
onClose: callback => {
handleCloseDialog("isOpenSignUp")
if (callback && typeof callback === "function") {
callback()
}
}
}
},
signInDialog: {
dialogProps: {
open: dialog.isOpenSignIn,
onClose: callback => {
handleCloseDialog("isOpenSignIn")
if (callback && typeof callback === "function") {
callback()
}
}
}
}
}}

如果你想在功能组件中使用上下文,你必须使用useContext Hook而不是Context.Consumer。

相关内容

  • 没有找到相关文章

最新更新