其一,调用HOC组件(是子组件)方法
import React from 'react';
const withRef = WrappedComponent => {
class HOC extends React.PureComponent {
constructor(props) {
super(props);
this.wrappedInstance = null;
}
getWrappedInstance() {
return this.wrappedInstance;
}
render() {
return <WrappedComponent ref={instance => this.wrappedInstance = instance} {...this.props} />;
}
}
return React.forwardRef((props, ref) => {
return <HOC {...props} forwardedRef={ref} />;
});
};
const MyComponent = React.forwardRef((props, ref) => {
return <div ref={ref}>{props.text}</div>;
});
const MyComponentWithRef = withRef(MyComponent);
class App extends React.Component {
componentDidMount() {
console.log(this.myComponentInstance);
}
render() {
return (
<MyComponentWithRef
text="Hello, World!"
ref={instance => this.myComponentInstance = instance}
/>
);
}
}
export default App;
常规方法
import React, { forwardRef, useImperativeHandle } from 'react';
const ChildComponent = forwardRef((props, ref) => {
const handleClick = () => {
console.log('ChildComponent clicked!');
};
useImperativeHandle(ref, () => ({
handleClick
}));
return (
<button onClick={handleClick}>点击</button>
);
});
export default ChildComponent;
eact 不允许组件访问其他组件的 DOM 节点。甚至自己的子组件也不行!这是故意的。Refs 是一种脱围机制,应该谨慎使用。手动操作 另一个 组件的 DOM 节点会使你的代码更加脆弱。
const MyInput = forwardRef((props, ref) => {
return <input {...props} ref={ref} />;
});