从props的children中获取ref
乔文飞 Lv8

props.children中处理ref

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Child extends React.Component {

render() {
return <div>Child</div>;
}
}

class GetRef extends React.Component {

componentDidMount() {
console.log(this.ref);
}

render() {
const childElement = React.Children.only(this.props.children);

return React.cloneElement(
childElement,
{ ref: el => this.ref = el }
);
}

}

class App extends Component {

render() {
return <GetRef><Child/></GetRef>;
}

}

结合转发ref将ref绑定到children组件中的div中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Com组件
interface Props {
forwardedRef: ref | null;
}
class Com extends React.Component<Props, State> {
render() {
const {forwardedRef} = this.props;
return <>
<div>
<div>
<div ref={forwardedRef}></div>
</div>
</div>
<>
}
}
const forwardRefCom = React.forwardRef((props, ref) => (
<Com forwardedRef={ref} {...props} />
));
return forwardRefCom;
  • 本文标题:从props的children中获取ref
  • 本文作者:乔文飞
  • 创建时间:2021-07-12 17:46:29
  • 本文链接:http://www.feidom.com/2021/07/12/从props的children中获取ref/
  • 版权声明:本博客所有文章为作者学习笔记,有转载其他前端大佬的文章。转载时请注明出处。