我有一个由父组件<HeatMap />
显示的图形质量较低的图形。HeatMap
有一个子组件<MyButton {...data}>
。MyButton
基本上是一个按钮,它加载图形图像。我的要求是:单击按钮后,父(HeatMap
)应该被重新呈现成一个高质量的svg图像。只有在那之后,下载才会发生。
我能够做到的是:在第一次点击按钮时,图像的质量会改变为svg,但是png图像会被下载。我认为下载在父文件被完全呈现之前就开始了。
代码:
class HeatMap extends Component {
constructor (props) {
super(props);
this.state = {
getSVG: false,
loadedData: [],
}
}
render () {
const { getSVG, loadedData } = this.state;
return (
<Fragment>
{getSVG
? <HeatmapSeries colorType="literal" data={loadedData} /> // svg graph
: <HeatmapSeriesCanvas colorType="literal" data={loadedData} />} // png(low-qlty)
<MyButton
{...this.props}
svgFunction={(required) => this.setState({ getSVG: true})}
getSVG={getSVG}
/>
</Fragment>
)
}
}
class MyButton extends Component {
render() {
return (
<Button size="small" icon="download" onClick={this._downloadSVG} >SVG</Button>
)
}
/**
* Generate the image and the download action
* @return {void}
**/
async _downloadSVG() {
const { svgFunction } = this.props;
if (typeof svgFunction === 'function') {
svgFunction(); // re-render the graph as a vector (try to re-render parent first)
}
methodToDownloadGraph({...this.props}); // graph svg is passed as argument
}
}
methodToDownloadGraph
的问题是: 在完成之前完成,而父母的重呈现则完成。是我想要实现的目标的图片:
发布于 2022-02-02 08:49:33
试试这个
async _downloadSVG() {
const { svgFunction } = this.props;
if (typeof svgFunction === 'function') {
await svgFunction(); // Add this line as it is
}
methodToDownloadGraph({...this.props}); // graph svg is passed as argument
}
发布于 2022-02-02 08:19:20
function的setState
是一个异步函数,这意味着它在调用状态后不会立即更新状态。如果您想在状态更新之后执行一些操作,那么需要将回调作为第二个参数传递给setState
函数。
要解决这个问题,您需要在methodToDownloadGraph
组件中调用HeatMap
函数,而不是Button
组件。
你可以这样做:
svgFunction={(required) => this.setState({ getSVG: true}, () => methodToDownloadGraph())}
https://stackoverflow.com/questions/70957068
复制相似问题