React函数组件和Class组件使⽤forwardRef传递ref // 函数组件使⽤forwardRef传递ref
const ForwardRefComponent = React.forwardRef((props, ref) => <div ref={ref.bind(this)} {...props}>⼦组件DOM</div>)
export default function TestRef() {
let myRef = null;
return (react面试题ref概念
<>
<button onClick={() => {
console.info(myRef);
}}>按钮</button>
<ForwardRefComponent ref={(r) => (myRef = r)} />
</>
)
}
// Class组件使⽤forwardRef传递ref
class Child extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div ref={this.props.forwardedRef}>这是⼦组件DOM</div>
)
}
}
const wrapper = function (InnerComponent) {
return React.forwardRef((props, ref) => {
return (
<InnerComponent forwardedRef={ref} {...props} />
)
})
}
const W = wrapper(Child)
class Parent extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<button onClick={() => {
console.Ref.current);
}}>按钮</button>
<W ref={Ref} { ...this.props}/>
</div >
)
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。