创建一个 child class,其中 child 可以在 React Native 的 parent class 中调用它的函数

Creating a child class where the child can call it's function in a parent class in React Native

假设我有以下代码作为我的 child class:

export class ChildComponent extends React.Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <View style = {styles.horizontalView}>
                {this.props.children}
                <TextInput
                    style={styles.textInput}
                    onChangeText = {() => { 
                        someFunction()
                        //call someFunction() in a parent class
                    }} 
                />
            </View>
        )
    }
}

现在,在我的 parent class 中,我希望能够执行以下操作:

export class ParentComponent extends React.Component {
    constructor(props) {
        super(props);
    }

    //someFunction is called by the child but is defined here by the parent.
    someFunction() {

    }

    render() {

    }
}

如果您有解决此问题的方法,请告诉我。再次感谢。

试试这个

export class ParentComponent extends React.Component {
    constructor(props) {
        super(props);
    }

    //someFunction is called by the child but is defined here by the parent.
    someFunction() {

    }

    render() {
       <ChildComponent parentFunction={this.someFunction}/>
    }
}

然后在childComponent中

export class ChildComponent extends React.Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <View style = {styles.horizontalView}>
                {this.props.children}
                <TextInput
                    style={styles.textInput}
                    onChangeText = {() => { 
                        //call someFunction() in a parent class
                        this.props.parentFunction();
                    }} 
                />
            </View>
        )
    }
}