[英]How to pass data from child to parent component using react hooks
I have a Parent component and couple of child components.我有一个父组件和几个子组件。 I need to disable or enable the button in the parent based on the ErrorComponent.
我需要根据 ErrorComponent 禁用或启用父级中的按钮。 If there is an error then I disable the button or else I enable it.
如果有错误,那么我禁用该按钮,否则我启用它。 I believe we can pass callbacks from the child to parent and let the parent know and update the button property.
我相信我们可以将回调从子级传递给父级,让父级知道并更新按钮属性。 I need to know how to do the same using react hooks?
我需要知道如何使用反应钩子来做同样的事情? I tried few examples but in vain.
我尝试了几个例子但徒劳无功。 There is no event on error component.
错误组件上没有事件。 If there is an error (props.errorMessage) then I need to pass some data to parent so that I can disable the button.
如果出现错误(props.errorMessage),那么我需要将一些数据传递给父级,以便我可以禁用该按钮。 Any help is highly appreciated
非常感谢任何帮助
export const Parent: React.FC<Props> = (props) => {
....
const createContent = (): JSX.Element => {
return (
{<ErrorPanel message={props.errorMessage}/>}
<AnotherComponent/>
);
}
return (
<Button onClick={onSubmit} disabled={}>My Button</Button>
{createContent()}
);
};
export const ErrorPanel: React.FC<Props> = (props) => {
if (props.message) {
return (
<div>{props.message}</div>
);
}
return null;
};
I'd use useEffect
hook in this case, to set the disabled
state depending on the message
props.在这种情况下,我将使用
useEffect
挂钩,根据message
道具设置disabled
的 state。 You can see the whole working app here: codesandbox你可以在这里看到整个工作应用程序: codesandbox
ErrorPanel
component will look like this: 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;
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.因此,根据
message
道具,只要它“存在”,我就会通过操纵道具传递的setDisabled
function 将disabled
道具设置为 true。
And to make this work, Parent
component looks like this:为了使它工作,
Parent
组件看起来像这样:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.