问题
I'm having a hard time understanding the docs on how to access the DOM ref of a child class component from the parent class component.
Parent.js:
import Child from './Child';
class Parent extends Component {
constructor(props) {
super(props);
this.refOfTheParent = React.createRef();
}
componentDidMount() {
const parentDOM = this.refOfTheParent.current;
//const childDOM = ???;
}
render() {
return (
<div ref={this.refOfTheParent}>
<Child />
</div>
);
}
}
export default Parent;
Child.js:
class Child extends Component {
render() {
return (
<div>Child component</div>
);
}
}
export default Child;
Could someone please finish this code for me where childDOM
in Parent::componentDidMount()
has the DOM ref of <Child />
.
Bonus: How would it look if Parent AND Child are both connected with react-redux connect.
回答1:
You can use forwardRef
class Child extend React.Component{
render() {
return (
<div ref={this.props.forwardRef}> Child component </div>
)
}
}
export default React.forwardRef((props, ref) => <Child {...props} forwardRef={ref} />)
Then in parent
constructor(props) {
// ...
this.childRef = React.createRef();
}
render() {
return (
<div>
<Child ref={this.childRef} />
</div>
)
}
more info here
回答2:
you can pass the ref in props in child component like
import React,{Component} from 'react';
import Child from './Child';
class Parent extends Component {
constructor(props) {
super(props);
this.refOfTheParent = React.createRef();
this.childRef=React.createRef();
}
componentDidMount() {
const parentDOM = this.refOfTheParent.current;
const childDom=this.childRef.current;
console.log(childDom);
//const childDOM = ???;
}
render() {
return (
<div ref={this.refOfTheParent}>
<Child childRef={this.childRef}/>
</div>
);
}
}
export default Parent
Child Component
import React,{Component} from 'react';
class Child extends Component {
render() {
return (
<div ref={this.props.childRef} id="1">Child component</div>
);
}
}
export default Child;
Demo
来源:https://stackoverflow.com/questions/53848512/how-to-get-the-dom-ref-of-a-child-class-component-in-a-parent-class-component