在 TypeScript 中,使用 TSX(TypeScript JSX)时,通过 refs
调用子组件的方法:
ParentComponent.tsx:
javascript
import React, { useRef } from 'react';
import ChildComponent, { ChildMethods } from './ChildComponent';
const ParentComponent: React.FC = () => {
const childRef = useRef<ChildMethods>(null);
const callChildMethod = () => {
if (childRef.current) {
childRef.current.childMethod();
}
};
return (
<div>
<ChildComponent ref={childRef} />
<button onClick={callChildMethod}>Call Child Method</button>
</div>
);
};
export default ParentComponent;
ChildComponent.tsx:
javascript
import React, { forwardRef, useImperativeHandle } from 'react';
interface ChildComponentProps {
// ... other props
}
export interface ChildMethods {
childMethod: () => void;
}
const ChildComponent = forwardRef<ChildMethods, ChildComponentProps>((props, ref) => {
const childMethod = () => {
console.log('Child method called from parent.');
};
useImperativeHandle(ref, () => ({
childMethod,
}));
return (
<div>
{/* Child component UI */}
</div>
);
});
export default ChildComponent;
你会看到