在React Native的父类中创建一个子类以供子类调用其函数

时间:2018-09-23 22:33:17

标签: react-native wrapper

说我的孩子班级有以下代码:

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>
        )
    }
}

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

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() {

    }
}

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

1 个答案:

答案 0 :(得分:1)

尝试一下

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>
        )
    }
}