国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

React根據寬度自適應高度的示例代碼

2019-11-19 15:12:06
字體:
來源:轉載
供稿:網友

有時對于響應式布局,我們需要根據組件的寬度自適應高度。CSS無法實現這種動態變化,傳統是用jQuery實現。

而在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生命周期

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 通城县| 磴口县| 德钦县| 临西县| 团风县| 邵阳县| 丘北县| 闽清县| 阿坝| 仁寿县| 昆山市| 丰台区| 阿拉善盟| 梓潼县| 澄江县| 云安县| 泽州县| 屏边| 平远县| 肥城市| 宁津县| 武清区| 中宁县| 大宁县| 萨迦县| 宁国市| 三原县| 瓦房店市| 通化市| 射洪县| 马龙县| 德阳市| 抚宁县| 石棉县| 灌阳县| 新泰市| 长宁区| 合江县| 冕宁县| 黎平县| 河津市|