如何将ref附加到撰写组件

时间:2017-08-08 17:31:52

标签: javascript reactjs

我目前正在尝试使用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>        
     )
  }
}

1 个答案:

答案 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>        
     )
  }
}
相关问题