社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
const FancyButton = React.forwardRef((props, ref) => ( <button ref={ref} className="FancyButton"> {props.children} </button> )); // You can now get a ref directly to the DOM button: const ref = React.createRef(); <FancyButton ref={ref}>Click me!</FancyButton>;
上述代码的解释:
1 function logProps(Component) {
2 class LogProps extends React.Component {
3 componentDidUpdate(prevProps) {
4 console.log('old props:', prevProps);
5 console.log('new props:', this.props);
6 }
7
8 render() {
9 const {forwardedRef, ...rest} = this.props;
11 // 把常规属性"forwardedRef"作为ref赋值给传过来的Component组件
12 return <Component ref={forwardedRef} {...rest} />;
13 }
14 }
15
16 // 注意React.forwardRef提供的第二个参数ref.
17 // 我们可以把ref作为一个常规属性"forwardedRef"传给LogProps这个组件
18 // 就可以跟实例绑定.
19 return React.forwardRef((props, ref) => {
20 return <LogProps {...props} forwardedRef={ref} />;
21 });
22 }
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!