默认不是函数反应类型错误

时间:2021-06-02 11:04:30

标签: reactjs typeerror speech-to-text

大家好,我想在 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;

1 个答案:

答案 0 :(得分:0)

这是因为这一行 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 

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

请看看这个Migration Guide