javascript - 如何在 React 中的窗口调整大小事件中设置 div 父节点以更改其宽度?
问题描述
该组件正在使用 jQuery 来获取正在工作的元素宽度。这是一个关于设置包装器 div 元素的问题,它的尺寸会随着窗口的大小而变化。目前它始终是 600 像素 x 300 像素。
当父容器达到一定大小时,我正在尝试更改 SVG React 组件的状态。容器是一个名为 withResizeHandler 的 React HOC,包装器节点是一个 div 元素。div 大小使用 jquery 从 resize 事件触发的回调 updateSize 检查。我更改了浏览器窗口大小并执行进入回调,但控制台日志表明该 div 从未改变其原始尺寸 600 像素 x 300 像素。代码在代码笔https://codepen.io/pboulos/pen/rrLYKE?editors=0111上。
const withResizeHandler = (WrappedComponent) => {
return class extends React.Component {
state = {
width: 0,
height: 0
}
//Init
componentWillMount(){
console.log('HOC Resize Props',this.props);
window.addEventListener("resize", this.updateSize.bind(this));
this.setState({width:this.props.width, height:this.props.height});
}
componentDidMount() {
this.updateSize();
}
componentWillUnmount(){
$(window).off('resize');
}
updateSize = () => {
// DOM node is the wrapper div element
var node = ReactDOM.findDOMNode(this);
const nodeWidth = $(node).width();
const nodeHeight = $(node).height();
console.log("Parent Width "+ nodeWidth+" Height "+nodeHeight);
if (nodeWidth < this.props.width){
this.setState({width: nodeWidth-20});
}else{
this.setState({width: this.props.width});
}
}
render () {
return (
<div style={{"height" : "300px"}}>
{/* pass down the props from the hoc wrapper */}
<WrappedComponent width={this.state.width} height={this.state.height}/>
</div>
);
}
}
}
解决方案
一个纯粹的 CSS 解决方案是在 SVG 组件上方和 App flex 根下方的 DOM 层次结构中的所有 div 节点上使用 inline-size(它仍然是实验性的)。对于反应样式示例:
<App>
<div style={{"inlineSize":"75%"}}>
<h3> Some Heading </h3>
<div style={{"inlineSize":"75%"}}>
<some SVG component>... </SVG>
</div>
<div>
</App>
推荐阅读
- php - 检查 php 登录站点中的用户活动
- php - PHP 警告:DOMDocument::loadHTML(): htmlParseEntityRef: 期待 ';' 在实体中,
- javascript - 如何使用 reactjs 状态从数组中的项目访问数据?
- python - 为什么 dict() 中的 key 比 Python3 中的 dict.get(key) 快?
- c# - .NET MultipartFormDataContent 不在 Content-Disposition 标头中发送文件名参数?
- c++ - 如何在 C++ 中的单行中从常量数组中返回一个值
- python - 如何将两个整数连接成一个字符串(python)?
- javascript - 如何使用 typed.js 使 div 元素居中
- c++ - 模板类的默认构造函数和遍历
- react-native - 如何在本机反应中根据呈现的屏幕更改 android:windowSoftInputMode 值