Reactjs 在NextJS中,当组件被withRouter包装时,如何使用ref访问该组件?
我有一个React组件,我将其导出如下:Reactjs 在NextJS中,当组件被withRouter包装时,如何使用ref访问该组件?,reactjs,next.js,Reactjs,Next.js,我有一个React组件,我将其导出如下: class Child extends Component { getStatus() { return 'I am child!'; } render() { return (<div>Child</div>); } } export default withRouter(Child) class Parent extends Component { constructor(props)
class Child extends Component {
getStatus() {
return 'I am child!';
}
render() {
return (<div>Child</div>);
}
}
export default withRouter(Child)
class Parent extends Component {
constructor(props) {
super(props);
this.childRef = createRef();
}
handleLogChildStatus = () => {
if (typeof this.childRef.current.getStatus === 'function') {
console.log(this.childRef.current.getStatus());
} else {
console.log(' Can not access to child component via ref! ');
}
}
render() {
return (
<div>
<Child ref={this.childRef} />
<div onClick={this.handleLogChildStatus}>Log child status</div>
</div>
);
}
}
类子级扩展组件{
getStatus(){
返回“我是孩子!”;
}
render(){
返回(儿童);
}
}
使用路由器导出默认值(子项)
我还有一个类需要“Child”组件的ref,如下所示:
class Child extends Component {
getStatus() {
return 'I am child!';
}
render() {
return (<div>Child</div>);
}
}
export default withRouter(Child)
class Parent extends Component {
constructor(props) {
super(props);
this.childRef = createRef();
}
handleLogChildStatus = () => {
if (typeof this.childRef.current.getStatus === 'function') {
console.log(this.childRef.current.getStatus());
} else {
console.log(' Can not access to child component via ref! ');
}
}
render() {
return (
<div>
<Child ref={this.childRef} />
<div onClick={this.handleLogChildStatus}>Log child status</div>
</div>
);
}
}
类父级扩展组件{
建造师(道具){
超级(道具);
this.childRef=createRef();
}
handleLogChildStatus=()=>{
if(typeof this.childRef.current.getStatus==='function'){
log(this.childRef.current.getStatus());
}否则{
log('Can not access to child component via ref!');
}
}
render(){
返回(
记录子项状态
);
}
}
此示例显示我无法访问子组件ref,因为它由withRouter HOC包装
我的问题是,当它被nextjs withRouter>包装时,我如何访问child ref组件?我认为下面的一个应该可以工作
export default withRouter(Child, { withRef: true })
第二种选择
this.childComponent = React.createRef();
....
<Child wrappedComponentRef={c => (this.childComponent = c)} />
this.childComponent=React.createRef();
....
(this.childComponent=c)}/>