0
有一個reactjs
組件,我需要在組件中獲得dom的高度。但是我失敗了,我不知道哪個是錯的。這是我的代碼:如何通過reactjs獲得dom的真實身高?
class ImgCropper extends React.Component {
constructor(props) {
super(props);
this.state = {
containSize: { width: 0, height: 0 },
};
}
componentDidMount() {
console.log('=================組件的寬高:', this.image.offsetWidth, this.image.offsetHeight);
this.middle.style.width = `${this.contain.offsetWidth}px`;
this.middle.style.height = `${this.contain.offsetWidth}px`;
// 配置圖片的寬高
this.image.style.transform = `translate(0px,${parseInt((this.contain.offsetHeight - this.image.height)/2, 10)}px)`;
}
render() {
return (<div ref={((div) => { this.contain = div; })} className={styles.container}>
<div id="cover-top" ref={(div) => { this.top = div; }} className={styles.coverTop}>
<a href="">
<input id="imageFile" name="image" type="file" accept="image/gif, image/jpeg, image/jpeg" />點擊上傳
</a>
<button >選擇圖片</button>
<input id="x" name="x" />
<input id="y" name="y" />
<input id="width" name="width" />
<input id="height" name="height" />
</div>
<div id="cover-middle" ref={(div) => { this.middle = div; }} className={styles.coverMiddle} />
<div id="cover-down" ref={(div) => { this.down = div; }} className={styles.coverDown}>
<button type="button" >獲得裁剪參數</button><span id="params">12121</span>
</div>
<img id="image" ref={(image) => { this.image = image; }} className={styles.image} draggable="true" src={test} />
</div>
);
}
控制檯日誌顯示DOM的高度爲0始終。
我嘗試,因爲你的代碼,但我得到一個例外:遺漏的類型錯誤:無法讀取屬性空的「形象」 –
對不起,我採取了一個錯誤,你是對的。感謝您的幫助! –