gpt4 book ai didi

reactjs - react中如何封装组件的useState?

转载 作者:行者123 更新时间:2023-12-05 01:59:43 27 4
gpt4 key购买 nike

我有以下示例代码:

export function SomeFormComponent() {
const [alertMessage, setAlertMessage] = useState("");
const [alertTitle, setAlertTitle] = useState("");
const [alertSeverity, setAlertSeverity] = useState("");


//to be called at the result of form result
const setAlert = (title, message, severity) => {
setAlertTitle(title);
setAlertMessage(message);
setAlertSeverity(severity);
}

return (<div>
<FormContents/>
<Alert severity={alertSeverity}>
<AlertTitle>{alertTitle}</AlertTitle>
{alertMessage}
</Alert>
</div>)
}

这是一个带有警告组件的表单,其中显示了获取的结果。我的问题是我在我的应用程序具有的每种形式中复制了这段代码 (useState(), setAlert(), )。我想知道是否有一种方法可以在不重复代码的情况下做到这一点。

最佳答案

创建自定义 Hook 和随附组件。该 Hook 提供了一个 setAlert() 函数,以及一个可以在组件上传播的 alert 对象。

useAlert 自定义 Hook - 您只需要一个带有包含所有值的对象的 setState:

const useAlert = () => {
const [alert, setAlert] = useState({ alertMessage: '', alertTitle: '', alertSeverity: '' });

return [
alert,
(alertMessage, alertTitle, alertSeverity) => {
setAlert({ alertMessage, alertTitle, alertSeverity });
}
]
}

AlertWrapper 组件:

const AlertWrapper = ({ alertSeverity, alertTitle, alertMessage }) => (
<Alert severity={alertSeverity}>
<AlertTitle>{alertTitle}</AlertTitle>
{alertMessage}
</Alert>
);

用法:

export function SomeFormComponent() {
const [alert, setAlert] = useAlert();

// use setAlert in your form
return (
<div>
<FormContents/>
<AlertWrapper {...alert} />
</div>
);
}

关于reactjs - react中如何封装组件的useState?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67653025/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com