React.js:如何通过react-audio-recorder获取子组件Blob音频状态数据
Hey there! Let's work through why you can't grab that WAV Blob data (audioData) from the <AudioRecorder/> component. Looking at your code snippet, I see a couple of obvious issues plus some better practices to fix this:
1. Fix those typos first!
This is probably the quickest win:
- You've got a typo in your method name:
handlClickis missing ane(should behandleClick). This means your binding in the constructor is pointing to a non-existent method, which could break the whole function. - Worse, you wrote
auidoDatainstead ofaudioDatawhen trying to access the state property. That's definitely why you're getting nothing here!
2. Stop accessing child component state directly (it's bad practice!)
Digging into a child component's internal state via refs is not recommended—component internals are meant to be encapsulated, and they might change with updates to the <AudioRecorder/> library. Instead, use the component's built-in callbacks to get the recorded data.
Most audio recorder components provide a prop like onStop that fires when recording finishes, passing the Blob data directly to your handler. Here's how to use it properly:
import AudioRecorder from 'react-audio-recorder'; class Test extends React.Component{ constructor(){ super(); this.handleRecordingStop = this.handleRecordingStop.bind(this); } handleRecordingStop(audioData) { // This gives you the WAV Blob directly! console.log("audioData:", audioData); // Now you can use this blob to upload to your server const formData = new FormData(); formData.append('audio', audioData, 'recording.wav'); // Add your upload logic here (fetch/axios call) } render() { return ( <AudioRecorder onStop={this.handleRecordingStop} // Make sure to set props to enable WAV format if needed format="wav" /> ); } }
3. If you must use refs (use cautiously!)
If you really need to access the component via a ref, make sure your ref is set up correctly, and double-check the component's state structure:
class Test extends React.Component{ constructor(){ super(); this.handleClick = this.handleClick.bind(this); this.audioRecorderRef = React.createRef(); } handleClick(){ // Optional chaining to avoid errors if the ref or state doesn't exist const audioData = this.audioRecorderRef.current?.state?.audioData; if (audioData) { console.log("audioData:", audioData); // Proceed with upload } else { console.log("No audio data found—did you finish recording?"); } } render() { return ( <> <AudioRecorder ref={this.audioRecorderRef} format="wav" /> <button onClick={this.handleClick}>Upload Recording</button> </> ); } }
4. Double-check the component's API
Different versions of react-audio-recorder might have different prop names or data structures. For example, some versions might store the Blob in a blob property instead of audioData, or require you to explicitly enable WAV output with a format prop.
内容的提问来源于stack exchange,提问作者Einere

