gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:10:02 29 4
gpt4 key购买 nike

例如。

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>
);
}
}

由于样式的原因,父组件中的整个 this.child ref 都发生了变化。请帮我解决这个问题,删除 withStyles 不是一个选项。

最佳答案

您可以使用 innerRef 属性并使用它来获取 child 的引用

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

export default withStyles(s)(Child);

在 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>
);
}
}

关于javascript - 使用 withStyles 导出子组件时如何访问父组件中的 refs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51552033/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com