react
父组件:使用createRef和useRef都可以
import {useRef} from 'react';
let ChildRef = useRef();
function handleOnClick() {
ChildRef.current.func();
}
<Child onRef={ChildRef} />
子组件:
const Child = props => {
props.onRef.current={
func
}
function func() {
console.log('执行我');
}
return <div>子组件</div>;
};
子组件第二种接收
import { useImperativeHandle} from 'react';
用useImperativeHandle暴露一些外部ref能访问的属性
useImperativeHandle(props.onRef, () => {
return {
func: func,
};
});
function func() {
console.log('调用了子组件方法');
}
vue
父组件
<template>
<child ref="child"></child>
<button @click="fatherMethod"></button>
</template>
<script>
methods: {
fatherMethod() {this.$refs.child.childMethods();
}
</script>
子组件
<script>
export default {
data() {
return {
name: '子组件'
};
},
methods: {
childMethods() {
console.log(this.name);
}
}
};
</script>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)