【问题标题】:How to be able to use a method outside its class in a function React Native如何能够在函数 React Native 中使用其类之外的方法
【发布时间】:2020-06-20 03:29:40
【问题描述】:

我很难在外部和函数中执行类方法

class Player extends Component {
  constructor(props) {
    super(props);
  }

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

}
export default Player;

我想做什么:

function() {
 Player.test();
}

class Player extends Component {
 constructor(props) {
  super(props);
 }

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

}
export default Player;

我尝试了几种方法在函数中运行此方法,但都没有帮助。

【问题讨论】:

标签: javascript react-native ecmascript-6 es6-class


【解决方案1】:

为此,您必须在要执行它的类的render 中包含Player。然后,为该Player 组件设置一个ref,然后通过ref 调用您的函数。

这是一个工作示例...

import React, { Component } from 'react';
import { Text, View } from 'react-native';
import Constants from 'expo-constants';


class Player extends Component {
  constructor(props) {
    super(props);
  }

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

  render() {
    return(
      null
    )
  }
}


export default class App extends Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    this.Player.test()
  }

  render() {
    return(
      <View>
        <Text>Test</Text>
        <Player ref={component => this.Player = component}/>
      </View>
    )
  }
}

【讨论】:

  • 抱歉回复晚了,但非常感谢您的帮助和愿意
  • 但我只是有一个疑问,你做的这个例子我需要这个应用程序类是一个函数而不是一个类,谢谢你的帮助:)
【解决方案2】:

您可以尝试使用静态方法:

The static keyword defines a static method for a class. Static methods aren't called on instances of the class. Instead, they're called on the class itself. These are often utility functions, such as functions to create or clone objects.

class ClassWithStaticMethod {
  static staticMethod() {
    return 'static method has been called.';
  }
}

console.log(ClassWithStaticMethod.staticMethod());
// expected output: "static method has been called."

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static

【讨论】:

    【解决方案3】:

    我的问题是:你需要 Player 成为一个组件吗?如果你不这样做,就这样做:

    function() {
     new Player().test();
    }
    
    class Player {
     test(){
      console.log('test')
     }
    }
    
    export default Player;
    

    【讨论】:

    • 我正在使用一个音乐播放器库,它是作为一个类构建的,但我的应用程序是以函数的形式开发的。所以我需要在我的函数中使用库类中的方法
    【解决方案4】:

    在 App 类中创建 Player 类对象

    var obj = new Player();
    
    now access method with the help of obj
    
    obj.test();
    

    【讨论】:

      猜你喜欢
      • 2019-09-01
      • 2016-11-30
      • 2021-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-25
      • 2015-02-16
      相关资源
      最近更新 更多