پاسخ داده شد
فرض کنید در parent component هستیم و می خواهیم متدی را در child component فراخوانی کنیم.
react react فراخوانی متد react child component react call a child's function from parent in React Trigger child function from parent component
- نفیسه افقی 6 ماه قبل سوال کرد
- شما باید برای ارسال دیدگاه وارد شوید
پاسخ عالی
بسته به اینکه child component چه نوع کامپوننتی است ( functional یا class ) دو راه دارید:
1- functional component
یک state
تعریف کنید و به عنوان prop
به child component بدهید. بعد در child component یک useEffect
تعریف کنید که با تغییر پیدا کردن این متغیر state اجرا شود و کار مورد نظر شما را انجام دهد:
const Child = props => {
useEffect(() => TriggeredFunc(), [props.buttonClicked]);
const TriggeredFunc = () => {
...
}
return '...';
}
const Parent = () => {
const [buttonClicked, setButtonClicked] = useState(0);
const onClick = e => {
setButtonClicked(buttonClicked++);
}
return <>
<button onClick={onClick}>My Button</button>
<Child buttonClicked={buttonClicked} />;
</>
}
2- class component
اگر کامپوننت را بصورت class تعریف کردید، می تواند از useRef برای اینکار کمک بگیرید (useRef برای functional component کار نمی کند، چون از این نوع کامپوننت نمی شود instance ساخت)
در child component:
const ChildComponent = React.forwardRef(({ actionButtons, ...props }, ref) => {
const [childDataApi, setChildDataApi] = useState(null);
const childFunction = () => {
// update childDataApi and pass it to parent
console.log("inside refreshEntireGrid");
}
useImperativeHandle(ref, () => ({
childFunction
}));
...
return ( ... );
});
در parent component:
const ParentComponent = (props) => {
const myRef = useRef();
const onClickFunction = () => {
myRef.current?.childFunction();
}
return (
<ChildComponent ref={myRef}/>
);
}
ش
- نفیسه افقی 6 ماه قبل پاسخ داد
- آخرین ویرایش 6 ماه قبل
- شما باید برای ارسال دیدگاه وارد شوید
پاسخ شما