1. class 组件中
通过传递this实例的方式
父组件:
import React, { Component } from "react";
import Child from './child'
export default class Parent extends Component {
componentDidMount(){
//调用子组件
this.child.test('参数')
}
onRef(ref){this.child = ref}
render() {
return (
<div>
<Child onRef={this.onRef} />
</div>
);
}
}
子组件
import React, { Component } from "react";
export default class Child extends Component {
componentDidMount(){
this.props.onRef(this)
}
//被调用方法
test(val){
alert('我是测试方法'+val)
}
render() {
return (
<div>
我是子组件
</div>
);
}
}
2. stateless(无状态组件)
(1) useImperativeHandle + forwardRef useimperativehandle官网
function FancyInput(props, ref) {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}));
return <input ref={inputRef} ... />;
}
FancyInput = forwardRef(FancyInput);
在本例中,渲染 <FancyInput ref={inputRef} /> 的父组件可以调用 inputRef.current.focus()
(2) 通过props funciton暴露出去
父组件
const [dagRefFunc, setDagRefFunc] = useState(null)
...
// 将子组件的方法存到state中
const updateDagRefFun = useCallback(
ref => {
if (ref) {
setDagRefFunc(ref())
}
},
[setDagRefFunc],
)
...
<Child dagRef={updateDagRefFun}/>
子组件
function ({dagRef}) {
...
// 方法暴露出去
useEffect(() => {
if (dagRef) {
dagRef(() => {
return {
updateItem: (id, config) => { },
updateAction: config => { },
}
})
return () => dagRef(undefined)
}
}, [dagRef])
}