Getting DOM node from React child element

后端 未结 6 1462
余生分开走
余生分开走 2020-12-04 17:14

Using the React.findDOMNode method that was introduced in v0.13.0 I am able to get the DOM node of each child component that was passed into a parent by mapping

6条回答
  •  甜味超标
    2020-12-04 18:06

    I found an easy way using the new callback refs. You can just pass a callback as a prop to the child component. Like this:

    class Container extends React.Component {
      constructor(props) {
        super(props)
        this.setRef = this.setRef.bind(this)
      }
    
      setRef(node) {
        this.childRef = node
      }
    
      render() {
        return 
      }
    }
    
    const Child = ({ setRef }) => (
        
    )

    Here's an example of doing this with a modal:

    class Container extends React.Component {
      constructor(props) {
        super(props)
        this.state = {
          modalOpen: false
        }
        this.open = this.open.bind(this)
        this.close = this.close.bind(this)
        this.setModal = this.setModal.bind(this)
      }
    
      open() {
        this.setState({ open: true })
      }
    
      close(event) {
        if (!this.modal.contains(event.target)) {
          this.setState({ open: false })
        }
      }
    
      setModal(node) {
        this.modal = node
      }
    
      render() {
        let { modalOpen } = this.state
        return (
          
    { modalOpen ? : null }
    ) } } const Modal = ({ close, setModal }) => (
    )

提交回复
热议问题