gpt4 book ai didi

javascript - 将 Metrics Graphics.js 与 React JS 结合使用

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:59:15 25 4
gpt4 key购买 nike

我正在尝试使用图形库 MetricsGraphs.js使用 React.js。与许多图形库一样,MetricsGraphics 通过直接改变 DOM 来工作。不幸的是,这在 ReactJS 中表现不佳。我尝试了很多不同的策略,但我似乎无法克服 MetricsGraphs.js 需要直接访问它可以变异的 DOM 元素这一事实。我是否忽略了任何事情,或者如果不对库进行认真修改就无法将 MetricsGraphics.js 与 React 一起使用?

最佳答案

您可以使用组件的 ref 属性来访问 React 中的 DOM 元素。

These refs (references) are especially useful when you need to: find the DOM markup rendered by a component (for instance, to position it absolutely), use React components in a larger non-React application, or transition your existing codebase to React.

您可以在 React refs documentation 中阅读有关 refs 的更多信息

这是一个在我今天的项目中有效的例子。

import React, { Component } from 'react';

import MG from 'metrics-graphics';
import './node_modules/metrics-graphics/dist/metricsgraphics.css'; // path to the CSS of metricsgraphics

class Graph extends Component {
componentDidMount() {
MG.data_graphic({
title: "Line Chart",
description: "This is a simple line chart.",
data: data,
width: 600,
height: 200,
right: 40,
target: this.target,
x_accessor: 'date',
y_accessor: 'value'
});
}

render() {
return <div ref={(ref) => this.target = ref}></div>;
}
}

export default Graph;

更新 由于文档中的一些注释,必须将 ref 更新为回调而不是字符串,以简化操作并使其在未来继续工作:

A note from Cautions section

If you want to preserve Google Closure Compiler Crushing resilience, make sure to never access as a property what was specified as a string. This means you must access using this.refs['myRefString'] if your ref was defined as ref="myRefString".

A note from the ref String Attribute section

Although string refs are not deprecated, they are considered legacy, and will likely be deprecated at some point in the future. Callback refs are preferred.

关于javascript - 将 Metrics Graphics.js 与 React JS 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31268920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com