如何使用反应钩子将数据从子组件传递到父组件 [英] How to pass data from child to parent component using react hooks
问题描述
我有一个父组件和几个子组件.我需要根据 ErrorComponent 禁用或启用父级中的按钮.如果出现错误,则禁用该按钮或启用它.我相信我们可以将回调从孩子传递给父母,让父母知道并更新按钮属性.我需要知道如何使用 React 钩子做同样的事情?我尝试了几个例子,但徒劳无功.错误组件上没有事件.如果出现错误 (props.errorMessage),那么我需要将一些数据传递给父级,以便我可以禁用该按钮.非常感谢任何帮助
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. 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. 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;
};
推荐答案
在这种情况下,我会使用 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;
这篇关于如何使用反应钩子将数据从子组件传递到父组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!