简体   繁体   中英

How to run a function when a prop updates within the same component?

I have a prop called transcript inside one of my components. It gets updated when I speak a voice intent. I would like to run a function anytime it changes which takes in the transcript as an argument

Here I am trying to do an OnChange={} function inside the span which I have loaded the transcript into but I know this method won't work, it was simply the easiest way of explaining what I wanted to accomplish


import React, { Component } from "react";
import SpeechRecognition from "react-speech-recognition";
import { Button } from 'react-bootstrap';


class Dictaphone extends Component {

highlightOnRead=(transcript, cursor)=>{

         console.log("transcript",transcript)
         console.log("cursor",cursor.anchorNode.parentNode.id) //we only need the word

         if(transcript.includes(" ")){
           transcript = transcript.split(" ").pop()
         }
         if(transcript = cursor.textContent.toLowerCase()){
             cursor.style.backgroundColor = 'yellow'; //highlight the span matching the intent
         }
         cursor = document.getElementById(cursor.anchorNode.parentNode.id).nextSibling.nextElementSibling;
               return cursor
     };



  render() {
   const {transcript, resetTranscript, browserSupportsSpeechRecognition} = this.props
    var cursor=''

    if (!browserSupportsSpeechRecognition) {
      return null
    }
    if(transcript==="notes"||transcript==="cards"||transcript==="home"|| transcript==="settings" || transcript==="read document"){
      this.libraryOfIntents(transcript,resetTranscript);
    }

    return (
      <div>
        <span id="transcriptSpan"className="transcriptspan" onChange={()=>{

          if(this.props.readAlongHighlightState===true){
            if(cursor===''){
              this.highlightOnRead(transcript,window.getSelection())
            }else{
                this.highlightOnRead(transcript,cursor)
            }
          }
        }}> {transcript}  </span>
        <Button variant="outline-dark" onClick={resetTranscript}>Reset</Button>
      </div>
    )
  }
}

export default SpeechRecognition(Dictaphone)

You can use lifecycle method called componentDidUpdate

componentDidUpdate(prevProps) {
  if (this.props.transcript !== prevProps.transcript) { // check if your props is changed
   // Make your function call here
  }
}

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