gpt4 book ai didi

reactjs - 将 react-charts 功能组件示例转换为类组件

转载 作者:行者123 更新时间:2023-12-04 11:47:08 33 4
gpt4 key购买 nike

嘿,我在尝试实现时遇到了很多麻烦 this example进入我的 React 项目。该示例与我的设置方式不同,我无法将其从他们的方式转换为我的方式。我有一个图表,但我真的希望包含渐变颜色。
这就是我所得到的......

import React from 'react'
import { Chart } from 'react-charts'

class GraphClub extends React.Component {
constructor(props) {
super(props)

this.state = {
chartData: [
{
label: 'Won',
data: [
[0, 0],
],
},
],
}
}


componentDidMount() {
//Get chartData
}

render() {
return (
<>
<Chart
data={this.state.chartData}
axes={[
{
primary: true,
type: 'linear',
position: 'bottom',
show: this.props.axis,
},
{
type: 'linear',
position: 'left',
show: this.props.axis,
},
]}
series={{ type: 'line', showPoints: false }}
tooltip
/>
</>
)
}
}

export default GraphClub
该图表有效,但是当我尝试添加颜色时,我无法走得很远而不会出错。希望得到一些帮助。
谢谢
我的第一个错误是 Error: Invalid hook call. Hooks can only be called inside of the body of a function component.这是显而易见的,因为它是一个类组件,而不是这一行的函数 const [{ activeSeriesIndex, activeDatumIndex }, setState] = React.useState({

最佳答案

前言
一些注意事项:

  • 向类组件的转换更加复杂,因为 React Charts 作者似乎以非标准的方式使用和创建钩子(Hook)。他们要么是天才,要么滥用钩子(Hook)系统将其用作美化的计算缓存。或两者。
  • 整个 React 生态系统正在转向函数组件。也许您有一个非常正当的理由使用类组件(我猜是与遗留代码互操作?),但是如果您仅仅因为这是学习 React 的方式而坚持使用类组件,我强烈建议您硬着头皮跑通过文档的 Hooks/Function Component 部分。不应该花很长时间来学习,它会让你的生活更轻松,无论如何你最终都必须这样做。

  • 转换为类组件
    首先,从 the repo中的示例代码开始,而不是该页面上的代码段,该代码段已经无法编译。
    接下来,将功能组件一一转换并验证每一步,然后再添加自己的代码。我已将更改上传到 a branch here .
    两个自定义 Hook useLagRadar()useDemoConfig()事实证明,示例中使用的转换为类组件太费力了,所以我只是将它们添加到高阶组件中。为此,我将 MyChart 类重命名为 MyChartInner 并创建了一个名为 MyChart 的新功能组件 HOC,它使用了上述 Hook 。
    import React from "react";
    import ReactDOM from "react-dom";

    import { Chart } from "react-charts";

    import useDemoConfig from "./useDemoConfig";
    import useLagRadar from "./useLagRadar";
    import ResizableBox from "./ResizableBox";
    import "./styles.css";

    export default class App extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
    activeSeriesIndex: -1,
    activeDatumIndex: -1,
    };
    }


    render() {
    const {
    activeSeriesIndex,
    activeDatumIndex,
    } = this.state;

    const setState = newState => this.setState(newState);

    return (
    <div>
    {JSON.stringify({ activeSeriesIndex, activeDatumIndex }, null, 2)}
    <MyChart
    elementType="line"
    setState={setState}
    activeDatumIndex={activeDatumIndex}
    activeSeriesIndex={activeSeriesIndex}
    />
    <MyChart
    elementType="area"
    setState={setState}
    activeDatumIndex={activeDatumIndex}
    activeSeriesIndex={activeSeriesIndex}
    />
    <MyChart
    elementType="bar"
    setState={setState}
    activeDatumIndex={activeDatumIndex}
    activeSeriesIndex={activeSeriesIndex}
    />
    </div>
    );
    }
    }

    const MyChart = props => {
    useLagRadar();
    // const { data, grouping, randomizeData } = useDemoConfig({
    const demoConfig = useDemoConfig({
    series: 4,
    height: 200,
    grouping: "primary",
    dataType: "ordinal",
    show: ["elementType", "grouping"]
    });
    return (
    <MyChartInner
    {...demoConfig}
    {...props}
    />
    );
    }

    class MyChartInner extends React.Component {
    constructor(props) {
    super(props);
    }

    render() {
    const {
    elementType,
    activeDatumIndex,
    activeSeriesIndex,
    setState
    } = this.props;

    //useLagRadar();


    const { data, grouping, randomizeData } = this.props;


    const series = {
    type: elementType
    };

    const axes = [
    {
    primary: true,
    type: "ordinal",
    position: "bottom"
    },
    {
    type: "linear",
    position: "left",
    stacked: true
    }
    ];

    const getSeriesStyle =
    series => ({
    color: `url(#${series.index % 4})`,
    opacity:
    activeSeriesIndex > -1
    ? series.index === activeSeriesIndex
    ? 1
    : 0.3
    : 1
    });

    const getDatumStyle =
    datum => ({
    r:
    activeDatumIndex === datum.index &&
    activeSeriesIndex === datum.seriesIndex
    ? 7
    : activeDatumIndex === datum.index
    ? 5
    : datum.series.index === activeSeriesIndex
    ? 3
    : datum.otherHovered
    ? 2
    : 2
    });

    const onFocus =
    focused =>
    setState({
    activeSeriesIndex: focused ? focused.series.id : -1,
    activeDatumIndex: focused ? focused.index : -1
    });

    return (
    <>
    <button onClick={randomizeData}>Randomize Data</button>
    <br />
    <br />
    <ResizableBox>
    <Chart
    data={data}
    grouping={grouping}
    series={series}
    axes={axes}
    getSeriesStyle={getSeriesStyle}
    getDatumStyle={getDatumStyle}
    onFocus={onFocus}
    tooltip
    renderSVG={() => (
    <defs>
    <linearGradient id="0" x1="0" x2="0" y1="1" y2="0">
    <stop offset="0%" stopColor="#17EAD9" />
    <stop offset="100%" stopColor="#6078EA" />
    </linearGradient>
    <linearGradient id="1" x1="0" x2="0" y1="1" y2="0">
    <stop offset="0%" stopColor="#FCE38A" />
    <stop offset="100%" stopColor="#F38181" />
    </linearGradient>
    <linearGradient id="2" x1="0" x2="0" y1="1" y2="0">
    <stop offset="0%" stopColor="#42E695" />
    <stop offset="100%" stopColor="#3BB2B8" />
    </linearGradient>
    <linearGradient id="3" x1="0" x2="0" y1="1" y2="0">
    <stop offset="0%" stopColor="#F4Ea0A" />
    <stop offset="100%" stopColor="#df4081" />
    </linearGradient>
    </defs>
    )}
    />
    </ResizableBox>
    </>
    );
    }
    }

    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);

    运行:
    # Clone the repo and checkout the branch
    git clone --branch stackoverflow-q68091135 https://github.com/codebling/react-charts.git

    # Switch to the "custom-styles" example directory
    cd react-charts/examples/custom-styles/

    # Install the dependencies
    npm i

    # Run the demo
    npm start

    关于reactjs - 将 react-charts 功能组件示例转换为类组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68091135/

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