前言
仅记录不同场景下ref使用,不断补充
解决方案
父组件class,子组件hooks场景
- 父组件中
constructor(props) {
super(props);
this.children = React.createRef(); //此处初始化
}
render() {
<Children ref={this.children}/>
}
- 子组件
const Children = (props, ref) => {
useImperativeHandle(ref, () => ({
hook
}));
const hook = () => {
console.info('消息打印')
};
return (
<div>
我是子级
</div>
)
};
export default forwardRef(Children);
父组件class,子组件hook或者class,但是有withRouter(react-router-dom
)路由包裹
1.父组件
constructor(props) {
super(props);
this.children = React.createRef(); //此处初始化
}
render() {
<Children wrappedComponentRef={this.children}/>
}
2.子组件(hook举列子)
const Children = (props, ref) => {
useImperativeHandle(ref, () => ({
hook
}));
const hook = () => {
console.info('消息打印')
};
return (
<div>
我是子级
</div>
)
};
export default withRouter(forwardRef(Children));
被高级组件包裹(此处举列自定义高级组件)
1.高级组件
export function withComponent(WrappedComponent) {
class Component extends React.Component {
render() {
return (
<WrappedComponent {...this.props} ref={this.props.forwardRef} /> //forwardRef为代理转发
)
}
}
return Component;
}
- 父级组件
constructor(props) {
super(props);
this.children = React.createRef(); //此处初始化
}
render() {
<Children forwardRef={this.children}/>
}
3.子级组件
const Children = (props, ref) => {
useImperativeHandle(ref, () => ({
hook
}));
const hook = () => {
console.info('消息打印')
};
return (
<div>
我是子级
</div>
)
};
export default withComponent(Children);
网友评论