【问题标题】:Is it possible to get ref of props.children?是否有可能获得 props.children 的参考?
【发布时间】:2019-02-12 00:29:08
【问题描述】:

我想获取 Child 组件的 ref。最好的方法是什么?

class Child extends React.Component {
  render() {
    return <div>Child</div>;
  }
}   

class GetRef extends React.Component {

  componentDidMount() {
     console.log(this.props.children.ref)
  }


  render() {
    return this.props.children
  }
}

编辑: 所以我可以这样使用它

<GetRef><Child/></GetRef>

【问题讨论】:

  • Child 和 GetRef 之间的联系是什么?
  • 你到底需要完成什么?
  • @OlivierBoissé 我添加了一个示例

标签: reactjs


【解决方案1】:

我假设GetRef children 只有 一个 child,那么您可以使用此代码检索唯一 child 组件的 ref

class Child extends React.Component {

  render() {
    return <div>Child</div>;
  }
}  

class GetRef extends React.Component {

  componentDidMount() {
    console.log(this.ref);
  }

  render() {
    const childElement = React.Children.only(this.props.children);

    return React.cloneElement(
      childElement, 
      { ref: el => this.ref = el }
    );
  }

}

class App extends Component {

  render() {
    return <GetRef><Child/></GetRef>;
  }

}

这是 stackblitz 上的 complete example

如果this.props.children 有多个孩子,您需要遍历孩子并将所有refs 存储到一个数组中

【讨论】:

  • 这会破坏孩子可能已经拥有的ref 道具,对吧?
【解决方案2】:

这是可以使用forwardRef 的地方:

class GetRef extends React.Component {
    render() {
        console.log(this.props.forwardRef)
    }
}

const ref = React.createRef();
<Child forwardRef={ref} />

或者,您也可以使用:

<Child ref="childRef" .../>


// In the parent component
React.findDOMNode(this.refs.childRef)

但是看看Exposing DOM Refs to Parent Components就知道是否使用ref:

在极少数情况下,您可能希望从父组件访问子组件的 DOM 节点。通常不建议这样做,因为它会破坏组件封装,但它有时对触发焦点或测量子 DOM 节点的大小或位置很有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-13
    • 2013-05-24
    • 2017-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多