例如。
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引用均已更改。请为我提供解决方法,不要选择withStyles。
答案 0 :(得分:1)
您可以使用一个innerRef道具,并使用它来获取孩子的ref
class Child extends Component {
componentDidMount() {
this.props.innerRef(this);
}
render() {
return (
<h1 ref={(ref)=>{this.ref = ref}}>Hello</h1>
);
}
}
export default withStyles(s)(Child);
和父项
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>
);
}
}
答案 1 :(得分:1)
让您的子组件具有onRef方法的道具,如下所示:
class Child extends Component {
componentDidMount() {
this.props.onRef(this);
}
render() {
return (
<h1 ref={(ref) => { this.ref = ref }}>Hello</h1>
);
}
}
然后在您的父方法中,您可以使用回调方法访问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>
);
}
}