调整可容纳SVG(d3)的React组件的大小 [英] Resizing React component that holds SVG (d3)

查看:189
本文介绍了调整可容纳SVG(d3)的React组件的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在简单的React应用中具有以下组件结构

I have following component structure in simple react app

<div id='app'>
 <Navbar />
 <Graph />
 <Footer />
</div>

导航栏的固定高度为80px

Navbar has fixed height 80px

页脚的高度固定为40px

Footer has fixed height 40px

Graph是一个d3-wrapper div,其中包含带有图形元素的SVG.

Graph is a d3-wrapper div that contains SVG with graph elements.

  1. 如何使Graph适应屏幕的剩余高度,使其始终占据屏幕的剩余高度?

  1. How to fit Graph into the remaining height of the screen so it always occupies the remaining height the screen?

如何在发生大小调整事件时更新包含d3-wrapper/SVG的react组件?

How to update react component containing d3-wrapper/SVG on resize event?

PS.因为我希望图形能够响应,所以我不应该对SVG的宽度和高度进行硬编码.

PS. As I want the graph to be responsive I should not hardcode width and height of the SVG.

此处是我试图解决此问题的codepen代码段.

Here is codepen snippet where I tried to solve this issue.

推荐答案

好,所以我找到了解决方案. 最简单的方法是将大部分工作留给CSS:

Ok so I have found solution for this. The shortest way is to leave majority of work to css:

.d3-wrapper {
  width: 100%;
  height: calc(100vh - #{$footerHeight + $navbarHeight}); 
}

svg {
 width: 100%;
 height: 100%;
}

然后在d3-wrapper组件中,如果需要,请创建对div的引用 并将clientWidth和clientHeight传递给svg组件作为道具.

Then in d3-wrapper component, if needed, create ref to the div and pass clientWidth and clientHeight to svg component as props.

要在调整大小时进行更新,请添加调整大小侦听器并使svg组件本身进行更新.

For on resize update, add resize listener and make svg component update itself.

这篇关于调整可容纳SVG(d3)的React组件的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆