ReactJS-Plotly图表无法完全填充容器,四周有空白边距如何解决
问题原因
layout配置格式错误:Plot组件的layout属性要求传入对象,你的代码错误传入了数组,导致margin、autosize等配置全部未生效autosize值类型错误:要求传入布尔值true,代码中传入了字符串'true',配置未生效- 外层容器无显式高度:ChartContainer包裹图表的div未设置宽高,导致图表的
width: 100%、height: 100%无参考基准,无法撑满容器
修复方案
1. 修正图表组件配置
以LineChart为例,调整Plot组件的layout参数:
import React from 'react' import Plotly from "plotly.js-strict-dist"; import createPlotlyComponent from "react-plotly.js/factory"; import {japan, canada, jhusa} from '../../tempdata' const Plot = createPlotlyComponent(Plotly); const LineChart = () => { return ( <Plot data={[japan, canada, jhusa]} layout={{ autosize: true, margin: { l: 0, r: 0, b: 0, t: 0, pad: 0 }, automargin: false }} style={{ width: '100%', height: '100%' }} config={{ displayModeBar: false, responsive: true }} /> ) } export default LineChart
所有类型的图表都需要做相同的layout格式修正。
2. 修正ChartContainer容器宽高
给ChartContainer的外层div设置100%宽高:
import React from 'react' import { Card,CardHeader, CardImg, CardText, CardBody, CardTitle, CardSubtitle, Button } from 'reactstrap'; import LineChart from '../LineChart'; import Table from '../Table'; import Treemap from '../Treemap'; const ChartContainer = ({chartType}) => { const displayChart = () => { if(chartType == 'treemap'){ return <Treemap /> } else if(chartType == 'line'){ return <LineChart /> }else if(chartType == 'table'){ return <Table /> } } return ( <div style={{width: '100%', height: '100%'}}> {displayChart()} </div> ) } export default ChartContainer
3. 修正MainPage的容器高度
给所有Row、Col父容器添加h-100类,确保高度继承链路完整:
<Row className="h-100"> <Col lg='4' className="h-100"> <ChartContainer chartType='treemap' /> </Col> <Col lg='4' className="h-100"> <ChartContainer chartType='line' /> </Col> <Col lg='4' className="h-100"> <ChartContainer chartType='line' /> </Col> </Row> <Row className="h-100"> <Col lg='4' className="h-100"> <ChartContainer chartType='table' /> </Col> <Col lg='4' className="h-100"> <ChartContainer chartType='table' /> </Col> <Col lg='4' className="h-100"> <Row className="h-100"> <Col className='h-50' lg='12'> <ChartContainer chartType='table' /> </Col> </Row> <Row className="h-100"> <Col className='h-50' lg='12'> <ChartContainer chartType='table' /> </Col> </Row> </Col> </Row>
同时确认页面最外层容器设置了足够高度,比如添加min-height: 100vh样式。
内容的提问来源于stack exchange,提问作者patrickli
相关产品推荐
相关产品推荐

