如何将语音识别的值传递到文本字段并在该值中编辑和查看控制台- reactjs

fhg3lkii  于 2023-01-02  发布在  React
关注(0)|答案(1)|浏览(109)
import React, { useState } from "react";
import TextField from "@mui/material/TextField";
import {} from "@fortawesome/free-solid-svg-icons";
import { Box, Chip, Grid, Typography } from "@mui/material";
import VoiceRecognice from "../component/VoiceRecognice";
import SpeechRecognition, {
  useSpeechRecognition,
} from "react-speech-recognition";
import IconButton from "@mui/material/IconButton";
import MicIcon from "@mui/icons-material/Mic";

const addDream = () => {
  const [story, setStory] = useState("");
  console.log(story);

  const {
    transcript,
    listening,
    resetTranscript,
    browserSupportsSpeechRecognition,
  } = useSpeechRecognition();

  if (!browserSupportsSpeechRecognition) {
    return <span>Browser doesn't support speech recognition.</span>;
  }
};

return (
  <>
    <Grid item xs={11}>
      <TextField
        label="Dream story"
        multiline
        rows={5}
        fullWidth
        value={transcript}
        onChange={(e) => setStory(e.target.value)}
      />
    </Grid>
    <Grid item xs={1}>
      <p>{listening ? "Mic On" : "Mic Off"}</p>
      <IconButton color="primary" onClick{SpeechRecognition.startListening}>
        <MicIcon />
      </IconButton>
    </Grid>
  </>
);
export default AddDream;

我想将浏览器支持语音识别值设置为TextField值。我想编辑该语音识别值。在我的代码中,没有编辑值,也没有获得输入值。但transcript值显示在TextField中。

vltsax25

vltsax251#

您可以使用useEffect钩子来使用transcript值更新story状态:

useEffect(() => {
    setStory(transcript);
  }, [transcript]);

然后在TextField中:

<TextField
   label="Dream story"
   multiline
   rows={5}
   fullWidth
   value={story}
   onChange={(e) => setStory(e.target.value)}
 />

相关问题