如何导出包含和功能的组件,然后在另一个组件中使用该功能?

时间:2015-08-22 03:11:47

标签: reactjs

我正在导出一个带有函数的组件,但是当我尝试在另一个组件中使用它的函数时,它会抛出一个未定义的。我已正确导入它但似乎无法使用这些功能。

import React from 'react';

export default class TeamStore extends React.Component {
    _state: {
        team: "None",
        loaded: false
    }

    getState() {
        return this._state.team;
    }

    addTeam(team) {
        this._state.team = team;
        this.onChange();
    }

    onChange() {}
}
import React from 'react';
import Jumbotron  from 'react-bootstrap/lib/Jumbotron';
import TeamStores from './TeamStore';

export default class JumbotronNews extends React.Component {
    getStateFromStore() {
        return  TeamStores.getState(); //this is the one throwing the error

    }

    constructor() {
        super();

        this.state = this.getStateFromStore();
    }

    componentDidMount() {
        TeamStore.onChange = this.onChange;
    }

    onChange() {
        this.setState(this.getStateFromStore());
    }

    render() {
        return (
                <Jumbotron>
                    <h1 style={{"marginLeft": "270px"}}>{this.state.team}</h1>

                  </Jumbotron>
        )
    }

}

2 个答案:

答案 0 :(得分:0)

我看到了一些问题。

  • 您将TeamStore定义为一个类,但您正在使用它,就像在其上定义了函数的常规对象一样。如果你想把它作为一个类,你必须在调用函数之前先将它实例化。

  • 您已将TeamStore类定义为React.Component的扩展名,但您并未将其用作React组件。

  • JumbotronNews文件中,您将TeamStore导入为TeamStores,但您将componentDidMount用作TeamStore

    < / LI>

答案 1 :(得分:0)

您想要的是 Mixin ,这是一个例子:

var SetIntervalMixin = {
  componentWillMount: function() {
    this.intervals = [];
  },
  setInterval: function() {
    this.intervals.push(setInterval.apply(null, arguments));
  },
  componentWillUnmount: function() {
    this.intervals.map(clearInterval);
  }
};

var TickTock = React.createClass({
  mixins: [SetIntervalMixin], // Use the mixin
  getInitialState: function() {
    return {seconds: 0};
  },
  componentDidMount: function() {
    this.setInterval(this.tick, 1000); // Call a method on the mixin
  },
  tick: function() {
    this.setState({seconds: this.state.seconds + 1});
  },
  render: function() {
    return (
      <p>
        React has been running for {this.state.seconds} seconds.
      </p>
    );
  }
});

在此页面上检查Mixin:https://facebook.github.io/react/docs/reusable-components.html

也可以使用基于ES6的不同实现:https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750