如何在React之外的对象上添加React方法

时间:2018-12-10 10:49:59

标签: javascript node.js reactjs highcharts react-highcharts

所以,这里的问题很简单。我正在使用React Highcharts Official,对于ReactHighcharts的options属性,我想从另一个文件导入graphOptions。

<ReactHighcharts highcharts={Highcharts} options={graphOptions} />

现在,这很容易,但是在我要导入的文件上,我有一个名为this.addData()的方法。

export const graphOptions = {
    title: {
        text: 'title '
    },
    yAxis: {
        title: {
            text: 'Points'
        }
    },
    xAxis: {
         title: {
            text: 'Date'
        }
     },
    series: this.addData()
};

好吧,所以我知道我可以在我的react render区域中保存此文件,但是如果我在我的系列代码中有this语句,是否可以将其导入到那里?

3 个答案:

答案 0 :(得分:1)

一种方法可能是导出函数即getGraphOptions而不是object,然后在导入后,将其与当前react类的this绑定。

export const function getGraphOptions() {
   return {
    // object
    series: this.addData()
}

并在react文件中。

import { getGraphOptions } from './...'
this.getGraphOptions = getGraphOptions.bind(this);

答案 1 :(得分:0)

您可以简单地将新属性分配给graphOptions中的constructor对象,并且已经可以使用适当的方法:

import options from "./options.js";

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

    options.series = this.addData();
    this.state = {
      options: options
    };
  }

  addData() {
    return [
      {
        data: [1, 2, 3]
      }
    ];
  }

  render() {
    return (
      <HighchartsReact highcharts={Highcharts} options={this.state.options} />
    );
  }
}

实时演示:https://codesandbox.io/s/m7xvq7z468

答案 2 :(得分:-1)

欢迎来到堆栈溢出:)

假设我们可以将您的对象转换为带有参数的函数,该参数是您要在其中使用的函数,然后返回一个对象。

示例:

export const getGraphOptions = (cb) => {
    title: {
        text: 'title '
    },
    yAxis: {
        title: {
            text: 'Points'
        }
    },
    xAxis: {
         title: {
            text: 'Date'
        }
     },
    series: cb()
};

因此,我们有getGraphOptions(cb)这个函数,它接收一个回调函数,并返回想要的对象,现在,在导入组件后,您可以在组件中找到类似的内容,也许在{{ 1}}方法:

render()

无需将组件用于不必要的逻辑工作。