gpt4 book ai didi

javascript - 如何能够在函数 React Native 中使用其类之外的方法

转载 作者:行者123 更新时间:2023-12-04 09:37:43 26 4
gpt4 key购买 nike

我很难在它之外和一个函数中执行一个类方法

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;

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

最佳答案

为此,您必须包含 Playerrender要执行它的类。然后,设置一个 ref到那个 Player组件,然后通过 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>
)
}
}

关于javascript - 如何能够在函数 React Native 中使用其类之外的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62481277/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com