简体   繁体   中英

Calling a method on a particular instance of a React component from another component

I'm trying to make a simple Pomodoro timer. I need to make the pause and stop buttons work. I defined a separate component called 'Timer' and added two buttons: 'Pause' and 'Stop' which obviously have to affect the state of the Timer.

How do I call the stop and pause method of Timer when the respective Buttons are pressed?

I understand that I can do this by simply including the buttons within the Timer class but I want to learn how to achieve something similar in the future and I'd like to keep the counter part of the Timer independent.

Here is the code:

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

class Timer extends React.Component{
  constructor (props){
    super(props)
    this.state = {
      minutes: props.minutes,
      seconds: props.seconds,
      count: 0,
    }
  }

  dec = () => {
      this.setState(previousState => {
        if (previousState.seconds==0){
          return {
            minutes: previousState.minutes-1,
            seconds: 59,
            count: previousState.count+1,
          }
        }
        else{
          return{
            minutes: previousState.minutes,
            seconds: previousState.seconds-1,
            count: previousState.count+1,
          }
        }
      });
  }
  componentDidMount (){
    setInterval(this.dec,1000);
  }

  render (){
    return(
      <View style = {{flexDirection: 'row'}}>
        <Text style = {styles.timerCount}> {this.state.minutes}</Text>
        <Text style = {styles.timerCount}>:</Text>
        <Text style = {styles.timerCount}> {this.state.seconds} </Text>
      </View>
      )
  }
   stop (){
    console.log('stop')
  }

  pause (){
   console.log('pause')
 }
}

export default class App extends React.Component {
  stop (){
    console.log('stop')
  }
  render() {
    return(
      <View style={styles.container}>
        <Timer style = {styles.timer} minutes={25} seconds = {0}/>
        <View style = {styles.buttonContainer}>
          <Button title = 'Pause' style = {styles.timerButton} color = 'white' onPress = {()=>{console.log("call the timer's pause method here")}}/>
          <Button title = 'Stop' style = {styles.timerButton} color = 'white' onPress = {()=>{console.log("call the timer's stop method here")}}/>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  buttonContainer: {
    flexDirection: 'row',
  },

  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: 50,
    backgroundColor: '#EC3D40',
  },

  timer: {
    backgroundColor: '#EC3D40',
    paddingTop: 50,
  },

  timerCount: {
    fontSize: 48,
    color: 'white',
    backgroundColor: '#EC3D40',
    paddingTop: 10,
    paddingBottom: 10,
  },

  timerButton:{
    borderColor: 'white',
    backgroundColor: 'transparent',
  }
});

Well actually you can do that using ref feature.

You can create a ref and assign it to your timer component. Then you can call this component's methods.

export default class App extends React.Component {
  timerRef = React.createRef();

  render() {
    return(
      <View style={styles.container}>
        <Timer style = {styles.timer} minutes={25} seconds = {0} ref={this.timerRef}/>
        <View style = {styles.buttonContainer}>
          <Button title = 'Pause' style = {styles.timerButton} color = 'white' onPress = {()=>{console.log("call the timer's pause method here"); this.timerRef.current.pause();}}/>
          <Button title = 'Stop' style = {styles.timerButton} color = 'white' onPress = {()=>{console.log("call the timer's stop method here"); this.timerRef.current.stop();}}/>
        </View>
      </View>
    );
  }
}

But this doesn't seem like a react way of doing things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM