首页 > 解决方案 > 默认不是函数反应类型错误

问题描述

大家好,我想在 React 组件中对文本进行语音。但是当我运行它时,我得到了这个错误: react_speech_recognition__WEBPACK_IMPORTED_MODULE_1___default(...) is not a function 有人可以告诉我该怎么做吗?

import React, { Component } from 'react'
import SpeechRecognition from 'react-speech-recognition'

class Mic extends Component {
  render() {
    const { transcript, resetTranscript, browserSupportsSpeechRecognition } = this.props

    if (!browserSupportsSpeechRecognition) {
      return null
    }
    
    return (
      <div>
        <button onClick={SpeechRecognition.startListening}>Start</button>
        <button onClick={SpeechRecognition.stopListening}>Stop</button>
        <button onClick={resetTranscript}>Reset</button>
        <p>{transcript}</p>
      </div>
    )
  }
}

export default SpeechRecognition(Mic)

在 app.js 中,我像这样运行它(如果有必要):

import React from 'react';
import logo from './logo.svg';
import './App.css';
import Container from './components/container/Container';
import Database from './components/database/Database';
import Mic from './components/mic/Mic';
import Test from './components/test/Test';

function App() {
  return (
    <Mic/>
    //<Test/>
  );
}

export default App;

标签: reactjstypeerrorspeech-to-text

解决方案


就是因为这条线SpeechRecognition(Mic)。错误指出模块的默认导出不是函数,这意味着它SpeechRecognition不是函数,因此您无法调用它。

将您的代码更改为

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

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

  if (!SpeechRecognition.browserSupportsSpeechRecognition()) {
    return null
  }

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

看起来您已经安装了最新版本,但尝试以旧方式使用它。

请查看此迁移指南


推荐阅读