我想從渲染函數訪問ref,並將其設置爲狀態。狀態未在componentDidMount中設置
這裏是我的代碼:
export default class App extends Component {
constructor(props) {
super();
this.arr = this.generateTimelineArray();
this.state = {el : 'empty'};
}
componentDidMount() {
this.setState({
el: this.refs.el
});
console.log(this.state.el)
}
render() {
return (
<div className="timeline__container--line" ref="el" ></div>
);
}
我可以console.log(this.refs.el)
和值記錄。但我必須將其保存到構造函數中,以將其傳遞給另一個組件。
問題是狀態沒有改變。
我在做什麼錯了?
在此先感謝
順便說一句你爲什麼要把dom元素引用到組件的狀態? –
我需要抵消div – Giedrius
[this.setState不更新值可能的重複](https://stackoverflow.com/questions/41278385/this-setstate-doesnt-update-value) –