React集成react-speech-recognition后转写文本不显示、状态不更新问题
问题原因及解决方案
核心问题
- 你错误地将
DictaphoneReact函数组件当作普通静态对象调用内部属性。React组件的内部状态是封闭的,无法直接从外部通过组件名访问,你在App类中写的Dictaphone.listening、Dictaphone.transcript获取的都是初始静态值,不会随语音识别状态更新同步变化。 - 你没有在App中渲染
Dictaphone组件,且该组件本身返回null。只有组件被正常挂载渲染时,内部的useSpeechRecognitionhook才会触发状态更新,当前配置下状态完全不会同步。
解决方案
方案1:将语音相关逻辑封装到Dictaphone组件内(推荐,适配类组件场景)
直接把所有语音识别相关的渲染逻辑放到Dictaphone.jsx中,再在App类里直接渲染该组件即可:
// Dictaphone.jsx 修改后代码 import { useSpeechRecognition } from 'react-speech-recognition'; import SpeechRecognition from 'react-speech-recognition'; const Dictaphone = () => { const { transcript, listening, resetTranscript, browserSupportsSpeechRecognition } = useSpeechRecognition(); if (!browserSupportsSpeechRecognition) { return <p>当前浏览器不支持语音识别功能</p> } return ( <div> <p>Microphone: {listening ? 'on' : 'off'}</p> <button onClick={SpeechRecognition.startListening}>Start</button> <button onClick={SpeechRecognition.stopListening}>Stop</button> <button onClick={resetTranscript}>Reset</button> <p>{transcript}</p> </div> ) }; export default Dictaphone
随后把App类中原有的语音相关渲染代码全部删除,替换为<Dictaphone />即可正常使用。
方案2:使用高阶组件包裹App类组件
如果你需要在App类中直接获取语音识别状态,可以用库提供的高阶组件withSpeechRecognition包裹App,无需单独编写Dictaphone组件:
// App.js 修改示例 import React, { Component } from 'react'; import SpeechRecognition, { withSpeechRecognition } from 'react-speech-recognition'; class App extends Component { render() { const { listening, transcript, resetTranscript } = this.props; return ( <div className="App"> <p>Microphone: {listening ? 'on' : 'off'}</p> <button onClick={SpeechRecognition.startListening}>Start</button> <button onClick={SpeechRecognition.stopListening}>Stop</button> <button onClick={resetTranscript}>Reset</button> <p>{transcript}</p> </div> ); } } export default withSpeechRecognition(App);
内容的提问来源于stack exchange,提问作者Soccerball123
相关产品推荐
相关产品推荐

