更新时间:2022-12-11 10:16:34
在这种情况下,我会使用 useEffect
钩子,根据 disabled
状态设置 disabled
代码>消息代码>道具.您可以在此处查看整个工作应用程序:codesandbox
I'd use useEffect
hook in this case, to set the disabled
state depending on the message
props. You can see the whole working app here: codesandbox
ErrorPanel
组件将如下所示:
import React, { useEffect } from "react";
interface IPropTypes {
setDisabled(disabled:boolean): void;
message?: string;
}
const ErrorPanel = ({ setDisabled, message }: IPropTypes) => {
useEffect(() => {
if (message) {
setDisabled(true);
} else {
setDisabled(false);
}
}, [message, setDisabled]);
if (message) {
return <div>Error: {message}</div>;
}
return null;
};
export default ErrorPanel;
因此,根据 message
道具,只要它存在",我就会通过操作传递的 setDisabled
函数将 disabled
道具设置为 true通过道具.
So depending on the message
prop, whenever it 'exists', I set the disabled
prop to true by manipulating the setDisabled
function passed by the prop.
为了实现这一点,Parent
组件看起来像这样:
And to make this work, Parent
component looks like this:
import React, { MouseEvent, useState } from "react";
import ErrorPanel from "./ErrorPanel";
interface IPropTypes {
errorMessage?: string;
}
const Parent = ({ errorMessage }: IPropTypes) => {
const [disabled, setDisabled] = useState(false);
const createContent = () => {
return <ErrorPanel setDisabled={setDisabled} message={errorMessage} />;
};
const handleSubmit = (e: MouseEvent) => {
e.preventDefault();
alert("Submit");
};
return (
<>
<button onClick={handleSubmit} disabled={disabled}>
My Button
</button>
<br />
<br />
{createContent()}
</>
);
};
export default Parent;