今天就跟大家聊聊有關使用React怎么根據寬度自適應高度,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
創新互聯建站從2013年創立,先為麟游等服務建站,麟游等地企業,進行企業商務咨詢服務。為麟游企業網站制作PC+手機+微官網三網同步一站式服務解決您的所有建站問題。
而在React中無需依賴于JQuery,實現相對比較簡單,只要在DidMount后更改width即可
Try on Codepen
需要注意的是在resize時候也要同步變更,需要注冊個監聽器
class Card extends React.Component {
constructor(props) {
super(props);
this.state = {
width: props.width || -1,
height: props.height || -1,
}
}
componentDidMount() {
this.updateSize();
window.addEventListener('resize', () => this.updateSize());
}
componentWillUnmount() {
window.removeEventListener('resize', () => this.updateSize());
}
updateSize() {
try {
const parentDom = ReactDOM.findDOMNode(this).parentNode;
let { width, height } = this.props;
//如果props沒有指定height和width就自適應
if (!width) {
width = parentDom.offsetWidth;
}
if (!height) {
height = width * 0.38;
}
this.setState({ width, height });
} catch (ignore) {
}
}
render() {
return (
<div className="test" style={ { width: this.state.width, height: this.state.height } }>
{`${this.state.width} x ${this.state.height}`}
</div>
);
}
}
ReactDOM.render(
<Card/>,
document.getElementById('root')
);參考資料

看完上述內容,你們對使用React怎么根據寬度自適應高度有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注創新互聯行業資訊頻道,感謝大家的支持。
文章標題:使用React怎么根據寬度自適應高度
URL地址:http://www.yijiale78.com/article0/jjpeoo.html
成都網站建設公司_創新互聯,為您提供Google、網站導航、搜索引擎優化、網站維護、網站制作、做網站
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯