直接上代码
import React, { useRef } from 'react';
const MyComponent = () => {
const myComponentRef = useRef(null);
const handleClick = () => {
myComponentRef.current.myMethod();
};
return (
<div>
<button onClick={handleClick}>调用组件方法</button>
<ChildComponent ref={myComponentRef} />
</div>
);
};
const ChildComponent = React.forwardRef((props, ref) => {
const myMethod = () => {
console.log('调用了组件方法');
};
React.useImperativeHandle(ref, () => ({
myMethod,
}));
return <div>子组件</div>;
});
export default MyComponent;
博客直接展示代码,涉及前端领域,运用了 JavaScript 和 React.js 相关技术。
5755

被折叠的 条评论
为什么被折叠?



