小编Div*_*lia的帖子

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

例如。

儿童.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 不是一种选择。

javascript reactjs material-ui

5
推荐指数
1
解决办法
1129
查看次数

标签 统计

javascript ×1

material-ui ×1

reactjs ×1