5

我的任务相当简单:我要做的就是将字体系列更改Roboto, sans-serif为 x 轴和 y 轴“刻度”(即沿两个轴的值)。

我可以通过以下方式更改 x 轴刻度的字体大小: <XAxis tick={{ fontSize: 'sans-serif!important' }} />

但这不起作用: <XAxis tick={{ fontFamily: 'sans-serif' }} />

我能看到的唯一其他选项是使用tickFormatter文档中指定的属性,它只接受一个函数,请参见此处:http ://recharts.org/#/en-US/api/XAxis

在这个项目中,我们使用 Recompose 实用程序库在 React 中使用函数式编程,因此我们以“纯”函数样式而不是普通的 React 类来渲染 JSX。

这是我能想到的最好的猜测是:

const xAxisTickFormatter = name => {
  return <div style={{ fontFamily: 'sans-serif' }}>{name}</div>;
};

export const LineChart = ({ data, isMobile }) => {
  console.log(data);
  return (
    <C
      width={isMobile ? 400 : 650}
      height={400}
      data={data}
      margin={{ top: 5, right: 20, left: 10, bottom: 5 }}
    >
      <XAxis
        tickFormatter={xAxisTickFormatter}
        dataKey="date"
        name="Date"
        style={{ fontFamily: 'sans-serif' }}
      />
      <YAxis />
      <CartesianGrid strokeDasharray="3 3" />
      <Tooltip wrapperStyle={{ fontFamily: 'Roboto, sans-serif' }} />
      <Legend
        wrapperStyle={{ fontFamily: 'Roboto, sans-serif' }}
        verticalAlign="bottom"
        height={36}
      />
      <Line
        type="linear"
        dataKey="price"
        name="Price"
        stroke="#8884d8"
        activeDot={{ r: 8 }}
      />
      <Line
        type="linear"
        dataKey="marketAverage"
        name="Market Average"
        stroke="#82ca9d"
      />
    </C>
  );
};

这会沿 x 轴输出 [object, Object],请参见屏幕截图:

在此处输入图像描述

文档中唯一类似的官方示例在此处使用旧createClass语法:https ://jsfiddle.net/alidingling/9y9zrpjp/

任何帮助将不胜感激,因为我已经在谷歌上搜索了尽可能多的类似问题,并且到目前为止在这个问题上花了大约半天的时间。

4

5 回答 5

9

为什么不只设置字体系列以及您想通过 CSS 覆盖的任何其他内容?

我们有类似的东西:

.recharts-cartesian-axis-tick {    
    font-size: 1.4rem;
    font-family: Roboto, sans-serif;
}
于 2018-06-28T09:04:34.913 回答
7

style属性对我来说很好;至少在 recharts 2.0.0-beta.1 中。

<XAxis
    dataKey="date"
    style={{
        fontSize: '1rem',
        fontFamily: 'Times New Roman',
    }}
/>
<YAxis
    style={{
        fontSize: '0.8rem',
        fontFamily: 'Arial',
    }}
/>

使用样式属性的轴中的字体大小和系列

你的tickFormatter函数应该只返回一个字符串,而不是一个 React 元素。

于 2020-03-28T07:03:12.787 回答
3

CSS 是最好的方法。但是,至少在一种情况下,您需要直接插入字体系列。尝试将 Recharts 组件从 SVG 转换为 PNG/JPEG 时,您的 CSS 不会呈现您设置的字体。

注意:您的 Recharts 在屏幕上呈现为 SVG。

在我的 CSS 中,我的字体为“Roboto”(第一张图片),当我转换为 PNG 时,我的字体呈现为“Times New Roman”(第二张图片)

在此处输入图像描述 在此处输入图像描述

要解决此问题,请执行以下操作:

  <XAxis
    fontFamily={'Roboto, sans-serif'}
  />
  <YAxis 
    fontFamily={'Roboto, sans-serif'}
  />
于 2020-03-05T21:36:11.523 回答
0

只需在父类中添加 className 属性,就像您的情况一样

<C className="fontName">

在CSS中

.fontName {
  font: normal normal 900 9px/12px Avenir; // font name 
  letter-spacing: -0.29px;
}
于 2021-02-12T13:42:23.407 回答
0

我很难改变轴刻度的颜色。实际上,我在“tick:{color...}”和“stroke”之间存在冲突,它们都会影响它。

于 2021-08-13T15:44:30.107 回答