使用withStyles导出子组件时如何访问父级中的refs?

Div*_*lia 5 javascript reactjs material-ui

例如。

儿童.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);
Run Code Online (Sandbox Code Playgroud)

父.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>
  );
 }
}
Run Code Online (Sandbox Code Playgroud)

由于使用样式,父组件中的整个 this.child ref 被更改。请帮我解决这个问题,放弃 withStyles 不是一种选择。

Aks*_*ayM 1

让你的子组件有一个带有 onRef 方法的 prop,如下所示:

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

  render() {
    return (
      <h1 ref={(ref) => { this.ref = ref }}>Hello</h1>
    );
  }
}  
Run Code Online (Sandbox Code Playgroud)

然后在父方法中,您可以使用回调访问 Child ref,如下所示:

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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)