我正在嘗試使用訪問組件方法,createRef()但是我收到TypeError: modalRef.current is null錯誤訊息。
我以前從未使用過 refs,所以如果它錯誤地指導了如何實作我想要做的事情。
這是我的嘗試
const parent = () => {
const modalRef = createRef();
const onBtnClick = () => {
modalRef.current.upadeState();
}
return(
<div>
<button onclick={onBtnClick}>bro</button>
<Modal ref={modalRef} />
</div>
)
}
模態
export default Modal = () => {
const upadeState = () => {
console.log('It works fam');
}
return(
<div>
bro we here
</div>
)
}
uj5u.com熱心網友回復:
為了從鉤子中的父組件呼叫子組件方法,我們使用React.forwardRef和React.useImperativeHandle鉤子。
下面是一個呼叫 child 方法的例子。
兒童.js
import React from "react";
const { forwardRef, useState, useImperativeHandle } = React;
// We need to wrap component in `forwardRef` in order to gain
// access to the ref object that is assigned using the `ref` prop.
// This ref is passed as the second parameter to the function component.
const Child = forwardRef((props, ref) => {
const [state, setState] = useState(0);
const getAlert = () => {
alert("getAlert from Child");
setState(state => state 1)
};
// The component instance will be extended
// with whatever you return from the callback passed
// as the second argument
useImperativeHandle(ref, () => ({
getAlert,
}));
return (
<>
<h1>Count {state}</h1>
<button onClick={() => getAlert()}>Click Child</button>
<br />
</>
);
});
父.js
import React from "react";
const { useRef } = React;
export const Parent = () => {
// In order to gain access to the child component instance,
// you need to assign it to a `ref`, so we call `useRef()` to get one
const childRef = useRef();
return (
<div>
<Child ref={childRef} />
<button onClick={() => childRef.current.getAlert()}>Click Parent</button>
</div>
);
};
子組件渲染并使用創建裁判React.useRef命名childRef。我們在父組件中創建的按鈕現在用于呼叫子組件功能childRef.current.getAlert();
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/337026.html
標籤:javascript 反应 反应钩子
