1. 类组件
class Content1 extends Component {
sub = React.createRef();
click = () => {
this.sub.current.click();
}
render() {
return (
<div className="content">
<Button onClick={this.click}>Btn1</Button>
<Sub ref={this.sub}/>
</div>
)
}
}
class Sub extends Component {
click () {
message.warning('hello Btn1!');
}
render() {
return (
<div style={{marginTop: '20px'}}>我是子组件</div>
)
}
}
class Content2 extends Component {
click = () => {
this.sub.click();
}
onRef = (ref) => {
this.sub = ref;
}
render() {
return (
<div className="content">
<Button onClick={this.click}>Btn2</Button>
<Sub onRef={this.onRef}/>
</div>
)
}
}
class Sub extends Component {
componentDidMount() {
this.props.onRef(this);
}
click () {
message.warning('hello Btn2!');
}
render() {
return (
<div style={{marginTop: '20px'}}>我是子组件</div>
)
}
}
forwardRef
const Content3 = () => {
const ref = useRef(null);
const click = () => {
ref.current.click();
}
return (
<div className="content">
<Button onClick={click}>Btn3</Button>
<Sub ref={ref}/>
</div>
)
}
const Sub = React.forwardRef((props, ref) => {
const click = useCallback(() => {
message.warning('hello Btn3!');
}, [])
useImperativeHandle(ref, () => ({
click
}), [click]);
return (
<div style={{marginTop: '20px'}}>我是子组件</div>
)
})
- 传props属性(可以不用forwardRef转发ref)
const Content4 = () => {
const ref = useRef(null);
const click = () => {
ref.current.click();
}
return (
<div className="content">
<Button onClick={click}>Btn4</Button>
<Sub t={ref}/>
</div>
)
}
const Sub = (props) => {
const click = useCallback(() => {
message.warning('hello Btn4!');
}, [])
useImperativeHandle(props.t, () => ({
click
}), [click]);
return (
<div style={{marginTop: '20px'}}>我是子组件</div>
)
}