将状态从组件传递到模态?

时间:2019-11-01 15:06:19

标签: javascript reactjs react-native

我有一个组件并将其导入到特定的屏幕中,在此屏幕中,当我单击打开模态包含组件时,我有一个按钮,它是一个“录音机”,因此在我录制声音后,我想将此声音保存到父屏幕中作为国家或其他事物!

在录音机组件中,我将语音数据保存到状态中!但是如何将其传递给其他父屏幕! 那我该如何处理呢?

这是镜头

父屏幕“单击添加语音后,我将显示模态”

Parent Screen

这是一个包含记录器组件的模态

Modal

代码

组件

  

“我将数据传递到componentDidMount内部的PassDataToModal状态”

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, TouchableOpacity, View} from 'react-native';
import {AudioRecorder, AudioUtils} from 'react-native-audio';
import Sound from 'react-native-sound';
import Icon from 'react-native-vector-icons/MaterialIcons';

class RecorderScreen extends Component {
  state = {
    PassDataToModal: null,
  };



  componentDidMount() {
    AudioRecorder.requestAuthorization().then(isAuthorised => {
      this.setState({hasPermission: isAuthorised});

      AudioRecorder.onFinished = data => {
        console.log('data', JSON.stringify(data));
        this.setState({PassDataToModal: data});

      };
    });
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.controls}>
          {this._renderPlayButton(() => {
            this._play();
          })}
          {this._renderRecordButton(this.state.recording)}
          {this._renderStopButton('Stop', () => {
            this._stop().then(() => this.setState({currentTime: 0}));
          })}
        </View>
        <Text style={styles.progressText}>{this.state.currentTime}s</Text>
      </View>
    );
  }
}

export default RecorderScreen;

父屏幕

import Modal from 'react-native-modal';
import RecorderScreen from './Recorder';

class Order extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isModalVisible: false,
    };
  }

  toggleModal = () => {
    this.setState({isModalVisible: !this.state.isModalVisible});
  };
 render() {
    return (
      <View style={styles.container}>
          <TouchableOpacity
            onPress={this.toggleModal}
           >
            <Icon name="mic" color="#333" size={20} />
            <Text style={{paddingHorizontal: 5}}>Add Voice</Text>
          </TouchableOpacity>
         <Modal
           style={{margin: 0}}
           isVisible={this.state.isModalVisible}
         >
           <View>
              <TouchableOpacity onPress={this.toggleModal}>
                <Icon name="close" color="#000" size={25} />
              </TouchableOpacity>

              <RecorderScreen /> // Component

            </View>
        </View>
     )
  }
}

1 个答案:

答案 0 :(得分:0)

在您的父组件中,将一个函数传递给您的SIGSEGV组件,该函数将向上发送必要的数据。 Docs on lifting state up

因此,在您的父母中,您会遇到类似的事情:

RecorderScreen

然后将该函数作为道具传递:

setData = (data) => {
  // Set this to whatever you need it to be named
  this.setState({childData: data});
}

最后,在需要的子对象中调用它(如果我遵循以下代码):

<RecorderScreen setData={this.setData} />

然后,您的父组件将有权访问您举起的孩子的数据。