Как вызвать родительскую функцию от ребенка в реагировать на нативный - PullRequest
0 голосов
/ 04 мая 2018

Я новичок, чтобы реагировать на родных. Я пытаюсь вызвать функцию от родителя в дочернем классе. Например: я создаю приложение, в котором есть кнопка, и когда вы нажимаете ее, она переносит вас на другую страницу. На другой странице есть кнопка, чтобы вернуться в главное приложение.

введите код здесь

import React, { Component } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';


export default class Parent extends Component {
    constructor(props) {
        super(props);
        this.state = {showForm: false}
        this.toggleForm = this.toggleForm.bind(this)
    }

    toggleForm = () => {
    this.setState(prevState => ({showForm:!prevState.showForm}))}


    render() {
        if (this.state.showForm) return <Test />
        return (
            <View style={styles.container}>
            <Text style={styles.paragraph}>
                Change code in the editor and watch it change on your phone!
                Save to get a shareable url.
            </Text>
            <Button onPress={this.toggleForm} title='test'/>
            </View>
        );
    }
}

export class Child extends Component {
    constructor(props) {    
        super(props);

        handleReturn = () => {
            this.props.toggleForm()
        }

        render() {
            return (
                <View style={{padding: 150}}>
                    <Text> Hello World</Text>
                    <Button onPress={this.props.toggleForm} title='return'/>
                </View>
            )
        }
    }
}

Спасибо за помощь!

1 Ответ

0 голосов
/ 04 мая 2018

В родительском компоненте вам необходимо отобразить дочерний компонент следующим образом:

render() {
    if (this.state.showForm) return <Test />
    return (
        <View style={styles.container}>
        <Text style={styles.paragraph}>
            Change code in the editor and watch it change on your phone!
            Save to get a shareable url.
        </Text>
        <Button onPress={this.toggleForm} title='test'/>
         ** <Child click={this.doSomething}/> **
        </View>
    );
}

А в вашем дочернем компоненте:

export class Child extends Component {
constructor(props) {    
    super(props);

    handleReturn = () => {
        this.props.toggleForm()
    }

    render() {
        return (
            <View style={{padding: 150}}>
                <Text> Hello World</Text>
               ** <Button onPress={this.props.click} title='return'/> **
            </View>
        )
    }
}

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...