React Native 调用回调函数

React native callling callback function

我的自定义组件上有一个函数,它基本上是一个回调函数,用于重新渲染 (this.setState()) 调用它的组件。

我正在努力解决这些调用的正确语法问题。你能帮忙吗?

自定义组件

export class LanguageSelector extends Component {

afterChange(callback: any){
    callback();
}

导入LanguageSelector的其他组件:

<LanguageSelector afterChange={() => { this.setState({}) }} ></LanguageSelector>

语言选择器

    import React, { Component } from 'react';
import {
    View,
} from 'react-native';
import { TouchableOpacity } from 'react-native';
import Flag from 'react-native-flags';
import { Global } from '../global'
import PropTypes from 'prop-types';

export class LanguageSelector extends Component {



    afterChange(callback: any) {
        callback();
    }

    changeLang(lang: string) {
        Global.localizedStrings.setLanguage(lang);
        //this.setState({});
    }

    render() {
        return (

            <View style={{ paddingBottom: 10, flexDirection: "row", alignSelf: "flex-end" }}>
                <TouchableOpacity onPress={() => this.changeLang('de')}>
                    <Flag code="DE" size={32} />
                </TouchableOpacity>
                <TouchableOpacity onPress={() => this.changeLang('en-US')}>
                    <Flag code="GB" size={32} />
                </TouchableOpacity>
            </View>

        )
    }
}

抱歉,我认为您使用的是 Typescript,您有这个选项,或者直接在您想要的地方使用 this.props.afterChange()。

interface LanguageSelectorProps{
   afterChange: () => void;
}
export class LanguageSelector extends Component<LanguageSelectorProps> {

     constructor(props) {
      super(props);
      this.afterChange = this.afterChange.bind(this);
    }

    afterChange() {
        this.props.afterChange(); // callback ,use whatever you want 
    }

    changeLang(lang: string) {
        Global.localizedStrings.setLanguage(lang);
        //this.setState({});
    }

    render() {
        return (

            <View style={{ paddingBottom: 10, flexDirection: "row", alignSelf: "flex-end" }}>
                <TouchableOpacity onPress={() => this.changeLang('de')}>
                    <Flag code="DE" size={32} />
                </TouchableOpacity>
                <TouchableOpacity onPress={() => {
                    this.changeLang('de')
                    this.afterChange(); 
                 }>
                    <Flag code="GB" size={32} />
                </TouchableOpacity>
            </View>

        )
    }
}