React Native将数据从组件发送到调用它的父组件

时间:2018-02-01 01:13:46

标签: javascript ios react-native

我正在开发一个使用我制作的计时器组件的本机应用程序,它的代码是:

import React, { Component } from 'react';
import {
    Platform,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from 'react-native';
import styles from '../styles/style';

export default class Timer extends Component<{}> {
    constructor(props) {
        super();
        this.state = {
            time: 10,
            timerStarted: false
        }
    }

    startTimer() {
        this.interval = setInterval(() => {
            this.setState({
                isFirstRender: !this.state.isFirstRender,
                time: this.state.time-1,
                isTimerRunning: true
            });
        }, 1000);
    }

    render() {
        if (!this.state.isTimerRunning)
            this.startTimer();

        return (
            <View style={styles.scoreBoard}>
                <Text style={styles.timerText}>Time: {this.state.time}</Text>
            </View>
        );
    }
}

此组件的状态值time,从10开始倒计时,每秒递减一次。当计时器到达零时,我需要它以某种方式通知在计时器完成时调用它的组件。在我的程序中,我的主要js文件是App.js,它在其渲染函数中调用我的计时器,如下所示:

render () {

        return (
            <View style={{flex: 1, flexDirection: 'row'}}>
                <View style={{flex: 1}}>
                    {/*This below is the component I need to return a value to this main class we are in*/}
                    <MyTimer />
                </View>
            </View>
        );
    }

我需要我的Timer类向主类返回一个值,可能是一个布尔值,表示时间已到。我最好的猜测是,也许我可以将我的主类的成员函数发送到Timer类作为道具,但我不确定这是否有效。我已经尝试了不同的方法来实现这一点,我知道你可以使用props将数据发送到组件,但是如何从组件中检索数据?谢谢。

1 个答案:

答案 0 :(得分:0)

您将一个函数从父级传递给子级,然后在子级中调用它以更新父级:

onTimerEnd = () => //do something in parent

render () {

        return (
            <View style={{flex: 1, flexDirection: 'row'}}>
                <View style={{flex: 1}}>
                    {/*This below is the component I need to return a value to this main class we are in*/}
                    <MyTimer onTimerEnd={this.onTimerEnd} />
                </View>
            </View>
        );
    }

另外我认为你应该在构造函数中启动计时器而不是渲染,每次组件重新渲染时都会调用render:

export default class Timer extends Component<{}> {
    constructor(props) {
        super();
        this.state = {
            time: 10,
        }
        this.startTimer(); //start timer
    }

    startTimer() {
        localTime = this.state.time;
        this.interval = setInterval(() => {
            this.setState({
                time: this.state.time-1,
            }, () => {
                if (this.state.time === 0) this.props.onTimerEnd() //invoke when timer hits 0
            });
        }, 1000);
    }

    render() {   
        return (
            <View style={styles.scoreBoard}>
                <Text style={styles.timerText}>Time: {this.state.time}</Text>
            </View>
        );
    }
}