通过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
count: {{ count }}
count2: {{ count2 }}
单文件写法(setup)
【通过vue3学习react17(二)|通过vue3学习react17(二) - 父组件调用子组件方法Ref(ts)】{{ count }}
推荐阅读
- 学习感悟篇|我的开源项目从0到1024的过程
- 图书管理系统简易版C++
- 机器学习|模型性能评价指标之AUC
- 机器学习|分类问题性能评价指标详述
- 机器学习|模型评价指标说明和scikit-learn代码实现
- 深度学习基础知识|深度学习的性能评价指标---图像分类的评价指标
- java|通过java将Excel表格导入数据到数据库
- 一起来学习C++的函数指针和函数对象
- OpenCV2学习笔记之视频流读取与处理
- async-validator|async-validator 源码学习笔记(三)(rule)