Как запустить функцию, когда реквизит обновляется в том же компоненте? - PullRequest
0 голосов
/ 22 октября 2019

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

Здесь я пытаюсь сделать функцию OnChange = {} внутри диапазона, в который я загрузил транскрипт, но я знаю этометод не сработает, это был просто самый простой способ объяснить, чего я хотел достичь


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)

1 Ответ

0 голосов
/ 22 октября 2019

Вы можете использовать метод жизненного цикла, который называется componentDidUpdate

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