通过vue3学习react17(二)|通过vue3学习react17(二) - 父组件调用子组件方法Ref(ts)

今天主要学习ref方法去调用子组件的方法, react hook和vue 单文件都使用到
喜欢的可以点赞
React
useRef 仅能用在 FunctionComponent,createRef 仅能用在 ClassComponent。
使用useRef 子组件(Child.tsx)

# Child.tsx export interface ChildProps { count: number; setCount: (params: ChildProps["count"]) => void; }const Child = (_props: any, ref: any) => { let [count, setCount] = useState(0); useImperativeHandle(ref, () => ({ count, setCount, })); return ({count}
); }; export default Child; # or export interface ChildProps { count: number; setCount: (params: ChildProps["count"]) => void; }interface refInterface { cRef: React.MutableRefObject; }const Child: React.FC = (props) => { const { cRef } = props; let [count, setCount] = useState(0); useImperativeHandle(cRef, () => ({ count, setCount, })); return ({count}
); }; export default Child;

父组件(Parent.tsx)
# Parent.tsx function Parent() { const childRef = useRef(); const updateChildState = () => { // changeVal就是子组件暴露给父组件的方法 childRef.current?.setCount(childRef.current?.count + 1); }; return ( ); }

createRef 子组件(Child.tsx)
import React, { useState } from "react"; interface ChildInterface { count: number; }class Child extends React.Component { constructor(props: React.FC) { super(props); this.state = { count: 0, }; } render() { return ({this.state.count}
); }setCount = (params: number) => { this.setState({ count: params, }); }; }export default Child;

父组件(Parent.tsx)
import Child from "./Child"; class Parent extends React.Component { childRef: RefObject; // childRef: LegacyRef | undefined; constructor(props: React.FC) { super(props); this.childRef = createRef(); }render() { return ( ); } updateChildCount = () => { let { setCount, state } = this.childRef.current as Child; setCount(state.count + 1); }; }export default Parent;

Vue3
父组件兼容二个写法
父组件(Parent.vue)
# Parent.vue

常规写法 子组件(Child.vue)
# Child.vue

单文件写法(setup)

    推荐阅读