You need to enable JavaScript to run this app. React使用react-speech-recognition报default is not a function错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

React使用react-speech-recognition报default is not a function错误如何解决

报错原因

该报错是因为你使用了3.x及以上版本的react-speech-recognition,该版本重构了API,不再支持旧版默认导入后作为高阶组件直接包裹组件的用法,导出规则和API调用方式都有调整。

修复步骤
  • 调整导入语句,将默认导入改为具名导入,引入高阶组件withSpeechRecognition和语音控制API
  • 修改API调用方式,startListening、stopListening方法会通过高阶组件注入到props中,无需直接从导入对象调用
  • 修改组件导出语句,使用withSpeechRecognition包裹你的类组件
  • 可选降级方案:如果不需要新版特性,也可以直接执行npm install react-speech-recognition@2.1.3安装旧版本,原有代码无需修改即可正常运行
修正后的完整Mic组件代码
import React, { Component } from 'react'
// 调整导入方式,具名导入所需对象
import { SpeechRecognition, withSpeechRecognition } from 'react-speech-recognition'

class Mic extends Component {
  render() {
    // 从props中获取注入的方法和状态
    const { transcript, resetTranscript, browserSupportsSpeechRecognition, startListening, stopListening } = this.props

    if (!browserSupportsSpeechRecognition) {
      return null
    }
    
    return (
      <div>
        <button onClick={startListening}>Start</button>
        <button onClick={stopListening}>Stop</button>
        <button onClick={resetTranscript}>Reset</button>
        <p>{transcript}</p>
      </div>
    )
  }
}
// 用withSpeechRecognition高阶组件包裹
export default withSpeechRecognition(Mic)
可选优化方案(函数组件写法)

如果你的项目支持React Hooks,更推荐使用官方提供的Hook写法,代码更简洁:

import React from 'react'
import { useSpeechRecognition } from 'react-speech-recognition'

const Mic = () => {
  const { transcript, resetTranscript, browserSupportsSpeechRecognition, startListening, stopListening } = useSpeechRecognition()

  if (!browserSupportsSpeechRecognition) {
    return null
  }

  return (
    <div>
      <button onClick={startListening}>Start</button>
      <button onClick={stopListening}>Stop</button>
      <button onClick={resetTranscript}>Reset</button>
      <p>{transcript}</p>
    </div>
  )
}

export default Mic

app.js的代码无需修改,按原来的方式引入使用即可。

内容的提问来源于stack exchange,提问作者dvid vid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 17:45:07