2016-12-30 55 views
4

我有一個特定的React-class的4個實例。 componentDidMount()後我想存儲每個實例的y位置。如何獲取componentDidMount()中的ReactJS元素?

我該如何解決呈現的元素?我不能使用classname,因爲我有4個具有不同位置的同一個類的元素。

我ReactJS組件:

const Col = React.createClass({ 
    componentDidMount: function() { 
     //here address the actual rendered col-instance 
    }, 

    render() { 
     return (
      <div className='col'> 
      </div> 
     ); 
    } 
}); 
+0

只是試圖瞭解更多的問題。你是否試圖存儲每個React組件實例的y位置以便稍後使用?安裝後每個元件的y位置也會發生變化嗎? – HussienK

+0

我需要存儲它,它不會改變。也許我可以使用this.ref? – vuvu

+1

你能否解釋一下你想要達到的目標?你想在哪裏存儲什麼?你想如何訪問存儲的值和從哪裏? –

回答

5

使用refs

首先,在每個JSX cols元素上掛接一個ref屬性。然後,在componentDidMount方法中使用此ref來訪問組件的DOM節點(實際的HTMLElement)。最後,獲取元素的位置/偏移或其他你需要的東西。

const Col = React.createClass({ 
    componentDidMount: function() { 
     // this.refs.col1 is the actual DOM element, 
     // so you can access it's position/offset or whatever 
     const offsetTop = this.refs.col1.offsetTop; 
    }, 

    render() { 
     return (
      <div className="col" ref="col1"> 
      </div> 
     ); 
    } 
}); 

PS:我不確定你說的元素y的位置是什麼意思。無論如何,一旦你知道如何獲得DOM元素(this.refs.col1),那麼你可以使用你需要的javascript to retrieve the position

+1

對於React.js的舊版API來說,這是一個很好的解決方案。從https://reactjs.org/docs/refs-and-the-dom.html:「我們建議不要這樣做,因爲字符串引用有一些問題,被認爲是遺留問題,並且可能會在將來的某個版本中刪除。 「用新的API這裏的解決方案:https://stackoverflow.com/questions/42242146/react-how-to-access-the-dom-element-in-my-render-function-from-the-same-compone – favero