繁体   English   中英

Javascript ES6(React)如何使用导入类的方法?

[英]Javascript ES6 (React) How to use a method of an imported class?

使用javascript ES6(React),我无法调用导入类的简单方法。

此代码有什么问题?

TypeError: WEBPACK_IMPORTED_MODULE_1__Seed .a.test不是函数

// App.js
import React from 'react';
import Seed from './Seed';

class App extends React.Component {

  constructor(props) {
    super(props);
    console.log('start1');
    Seed.test();
  }

  render() {
    return("ei");
  }

}

export default App;

// Seed.js
import React from 'react';

class Seed extends React.Component {

  constructor(props) {
    super(props);
    console.log('seed1');
  }

  test() {
    console.log('seed test');
  }

};

export default Seed;

你可以这样声明测试为静态

class Seed extends React.Component {

  static test() {
    console.log('seed test');
  }

  constructor(props) {
    super(props);
    console.log('seed1');
  }

};

如果要在Seed组件中进行调用test ,请使用Seed.test()

您不能像这样访问类的方法,因为它不是static

您需要使用<Seed />渲染App并获得对该组件的引用

// App.js
import React from 'react';
import Seed from './Seed';

class App extends React.Component {
  constructor(props) {
    super(props);
    console.log('start1');
    this.seedRef = React.createRef();
  }

  componentDidMount() {
    // seedRef is the Seed instance
    this.seedRef.current.test();
  }

  render() {
    return(<Seed ref={this.seedRef} />);
  }
}

export default App;

选择很少,具体取决于您要执行的操作

1)如果此功能与Seed实例无关,则将其设为静态。

class Seed extends React.Component {
  static test() {
    console.log('seed test');
  }
  // ...etc
}

然后,您可以像调用它一样调用它。

2)如果需要将其绑定到种子的特定实例,则可以将其重新命名,然后调用它。 例如:

const mySeed = new Seed();
mySeed.test();

鉴于Seed是一个react组件,这很可能不是您想要的,因为您应该让react实例化组件,然后通过prop与之交互

3)使用refs让react给您提供对该组件的引用。 我假设您使用的是React 16或更高版本,因此可以访问React.createRef

constructor(props) {
  super(props);

  this.seedRef = React.createRef();
}

componentDidMount() {
  this.seedRef.current.test();
}

render() {
  return <Seed ref={this.seedRef}/>
}

这样比较好,但是您仍然想直接与该组件进行交互仍然令人怀疑。

4)使用道具,不要直接叫它。 确切的执行方法取决于您要执行的操作,但是假设您只想在某些条件为真时才调用该方法。 然后,您可以将一个prop传递给Seed,种子将调用方法本身。

// in App:

render() {
  render <Seed shouldDoStuff={true} />
}

// In seed:

constructor(props) {
  super(props);
  if (props.shouldDoStuff) {
    this.test();
  }
}

暂无
暂无

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

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