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

时间:2018-06-28 08:54:51

标签: reactjs functional-programming recharts

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

我可以使用以下方法更改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],请参见屏幕截图:

enter image description here

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

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

4 个答案:

答案 0 :(得分:4)

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

我们有类似的东西:

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

答案 1 :(得分:2)

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

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

font size and family in axes using style attribute

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

答案 2 :(得分:1)

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

注意:您的图表在屏幕上显示为SVG。

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

enter image description here enter image description here

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

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

答案 3 :(得分:0)

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

<C className="fontName">

在 css 中

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