简体   繁体   中英

react native TouchableOpacity, different functions by first and second click

I'm creating a simple text-to-speech function for my react native app. I have a button, when you click it for the first time, it will read the text and play the sound. But I want to make it dynamic. For example: If you click again it should stop, if click again, should play again, etc..... But now, it is only available for playing the sound with any click. Where/how should I execute the stopReadText()? I still don't have any idea about this. Thanks a lot.

Here is the code:

const readText = () => {
    Speech.speak('text')
  }

const stopReadText = () => {
    Speech.stop()
  }

  return (
    <View>
      <TouchableOpacity onPress=(readText)>
        <Divider style={styles.modalDivider} />
        <Image
          style={styles.speaker}
          source={require('../../assets/speaker.png')}
        />
      </TouchableOpacity>
    </View>
  )

(I am using expo-speech)

You can do it by taking on a boolean state variable:

import { useState } from 'react';

const [isPlay,setIsPlay]=useState(false)

const readText = () => {
    Speech.speak('text')
  }

const stopReadText = () => {
    Speech.stop()
  }

const handlePlay =() =>{
  if(!setIsPlay){
      readText()
      setIsPlay(true)
  }
  else {
      stopReadText()
      setIsPlay(false)
  }

 }


  return (
    <View>
      <TouchableOpacity onPress={handlePlay}>
        <Divider style={styles.modalDivider} />
        <Image
          style={styles.speaker}
          source={require('../../assets/speaker.png')}
        />
      </TouchableOpacity>
    </View>
  )

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