如何更改 React Recharts 库 X 轴/Y 轴刻度的字体系列?

How to change font family for React Recharts library X-axis / Y-axis ticks?

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

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

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

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

在这个项目中,我们使用 Recompose 实用程序库在 React 中使用函数式编程风格,因此我们以 "pure" 函数风格而不是普通 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/

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

为什么不直接通过 CSS 设置字体系列和您想要覆盖的任何其他内容?

我们有类似的东西:

.recharts-cartesian-axis-tick {    
    font-size: 1.4rem;
    font-family: Roboto, sans-serif;
}

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

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

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



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

  <XAxis
    fontFamily={'Roboto, sans-serif'}
  />
  <YAxis 
    fontFamily={'Roboto, sans-serif'}
  />

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 函数应该 return 只是一个字符串,而不是 React 元素。

只需在父级 class 中添加 class名称 属性 就像您的情况一样

<C className="fontName">

并在 css

.fontName {
  font: normal normal 900 9px/12px Avenir; // font name 
  letter-spacing: -0.29px;
}

我很难尝试更改坐标轴刻度线的颜色。实际上,我在 "tick:{color...}" 和 "stroke" 之间发生了冲突,这两者都会影响它。