简体   繁体   中英

how to access refs in parent when child component is exported with withStyles?

for eg.

Child.js

//assume there is s as styles object and used in this component
class Child extends Component {
 render() {
  return (
    <h1 ref={(ref)=>{this.ref = ref}}>Hello</h1>
  );
 }
}

export default withStyles(s)(Child);

Parent.js

class Parent extends Component {
 onClick() {
    console.log(this.child) // here access the ref
    console.log(this.child.ref) // undefined
 }
 render() {  
  return (
    <div>
      <Child ref={child => this.child = child} />
      <button onClick={this.onClick.bind(this)}>Click</button>
    </div>
  );
 }
}

due to with styles the whole this.child ref in the parent component is changed. Please help me out with a workaround for this, dropping the withStyles is not an option.

You can make use of an innerRef prop and use it to get the ref of the child like

class Child extends Component {
 componentDidMount() {
    this.props.innerRef(this);
 }
 render() {
  return (
    <h1 ref={(ref)=>{this.ref = ref}}>Hello</h1>
  );
 }
}

export default withStyles(s)(Child);

and in parent

class Parent extends Component {
 onClick() {
    console.log(this.child) // here access the ref
    console.log(this.child.ref) // undefined
 }
 render() {  
  return (
    <div>
      <Child innerRef={child => this.child = child} />
      <button onClick={this.onClick.bind(this)}>Click</button>
    </div>
  );
 }
}

Have your child component a prop with method onRef like follows:

class Child extends Component {
  componentDidMount() {
    this.props.onRef(this);
  }

  render() {
    return (
      <h1 ref={(ref) => { this.ref = ref }}>Hello</h1>
    );
  }
}  

Then in your parent method you can access Child ref using callback as follows:

class Parent extends Component {
  onClick() {
    console.log(this.childHoc) // here access the withStyle ref
    console.log(this.actualChild) // here access the actual Child Component ref
  }
  render() {
    return (
      <div>
        <Child ref={childHoc => this.childHoc = childHoc} onRef={actualChild => this.actualChild = actualChild} />
        <button onClick={this.onClick.bind(this)}>Click</button>
      </div>
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM