簡體   English   中英

當同一組件中的道具更新時,如何運行 function?

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

我的一個組件中有一個名為 transcript 的道具。 當我說出語音意圖時,它會更新。 我想在 function 任何時候運行它,它以成績單作為參數

在這里,我嘗試在已加載成績單的跨度內執行 OnChange={} function 但我知道這種方法行不通,它只是解釋我想要完成的最簡單的方法


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)

您可以使用名為componentDidUpdate的生命周期方法

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM