我目前正在尝试使用ref
以下列方式获取子组件功能,但它没有显示任何细节。
class ChildCompent extends React.Component {
constructor(props){
super(props);
}
_function1 =()=>{
/* ...... */
}
_function1 =()=>{
/* ...... */
}
render (){
return (
<div>
ChildComponent
</div>
)
}
}
let ComposedChild = compose(
/* --- graphql query */
)(ChildComponent);
class ParentComponent extends React.Component {
constructor(props){
super(props);
}
_onClick = ()=>{
console.log(this.refs.childComponent)
// doesn't show the _function1 and _function2
}
render (){
return (
<div onClick={this._onClick}>
<div>Testing</div>
<ChildComponent ref="childComponent"/>
</div>
)
}
}
答案 0 :(得分:0)
您应该使用ref回调来为组件设置ref 看到这个答案:
How to access a DOM element in React? What is the equilvalent of document.getElementById() in React
之后,为了访问其他组件的功能,您可以像this.childComponent._function1()
此外,您需要使用在ParentComponent中使用compose函数包装后返回的组件。
class ChildComponent extends React.Component {
constructor(props){
super(props);
}
_function1 =()=>{
/* ...... */
console.log('hello');
}
render (){
return (
<div>
ChildComponent
</div>
)
}
}
let ComposedChild = compose(
/* --- graphql query */
)(ChildComponent);
class ParentComponent extends React.Component {
constructor(props){
super(props);
}
_onClick = ()=>{
this.childComponent._function1()
// doesn't show the _function1 and _function2
}
render (){
return (
<div onClick={this._onClick}>
<div>Testing</div>
<ComposedChild ref={(ref) => this.childComponent = ref}/>
</div>
)
}
}