繁体   English   中英

在React.Component的ES6类实例上调用方法

[英]Call method on ES6 class instance of React.Component

我是React的新手,我将它与ES6类结合使用。 我有一个继承自React.Component的类,并根据其state的单个属性呈现DOM。 这是看起来如何:

class LoadingScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = { state: 'isHidden' };

  showTrying() {
    this.setState({ state: 'isTrying' });
  }

  hideAll() {
    this.setState({ state: 'isHidden' });
  }

  render() {
    switch (this.state.state) {

    case 'isHidden':
      return null;

    case 'isTrying':
      // Returns a bunch of DOM elements
  }
}

在父类中,这不是React组件(我试图迁移不使用框架的现有代码),我想:

  1. 创建LoadingScreen的实例
  2. 调用React.render将其插入DOM中
  3. 在该实例上调用hideshowTrying等方法来更新其状态

我试过了:

this.loadingScreen = new LoadingScreen();
React.render(this.loadingScreen, mountNode); // React invalid component error

// Later on...
this.loadingScreen.showTrying();

并尝试过:

this.loadingScreen = React.render(React.createElement("LoadingScreen"), mountNode);

// Later on...
this.loadingScreen.showTrying(); // Undefined is not a function

显然我在这里缺少一些基本的东西。 :)

更常见的是,您在LoadingScreen组件实例上设置属性以控制内部表示的可见性,而不是通过对象实例上的函数调用来调整状态。

class LoadingScreen extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    switch (this.props.mode) {
        case 'isHidden':
          return null;
        case 'isTrying':
          // Returns a bunch of DOM elements
    }
  }
}

LoadingScreen.propTypes = { 
    mode: React.PropTypes.string
};
LoadingScreen.defaultProps = { 
    mode: 'isTrying'
};

然后,从父母那里,你会做这样的事情,例如:

var currentMode = "isTrying";
React.render(<LoadingScreen mode={ currentMode } />, mountNode);

或者,另一种模式是父容器/组件使用属性的值(我称之为mode ),根本不创建和渲染LoadingScreen组件。

如果需要LoadingScreen ,您可以将property值复制到本地状态。

你的第二种方法很接近。

React.createElement的第一个参数可以是字符串(div,span等)或React.Component的子类。 在您的情况下,第一个参数应该是LoadingScreen

this.loadingScreen = React.render(React.createElement(LoadingScreen), mountNode);

this.loadingScreen.showTrying(); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM