[英]Pass state from component to Modal?
我有一個組件並將其導入特定屏幕,在這個屏幕上我有一個按鈕,當點擊時我打開模式包含組件它是一個“錄音機”所以在我錄制聲音后我想把這個聲音保存到父屏幕中作為 state或者其他的東西!
在錄音機組件中,我將語音數據保存到 state 中? 但我怎樣才能將它傳遞給其他父屏幕? 那么我該如何處理呢?
這是鏡頭
父屏幕“單擊添加語音后我顯示模態”
這是一個包含記錄器組件的模態
代碼
零件
“我在 componentDidMount 內將數據傳遞給 PassDataToModal state”
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>
)
}
}
在您的父組件中,將 function 傳遞給您的RecorderScreen
組件,該組件將向上發送必要的數據。 關於提升 state 的文檔。
所以在你的父母中,你會有類似的東西:
setData = (data) => {
// Set this to whatever you need it to be named
this.setState({childData: data});
}
然后將 function 作為道具傳遞:
<RecorderScreen setData={this.setData} />
最后,根據需要在孩子中調用它(如果我遵循這樣的代碼):
componentDidMount() {
AudioRecorder.requestAuthorization().then(isAuthorised => {
this.setState({hasPermission: isAuthorised});
AudioRecorder.onFinished = data => {
this.props.setData(data);
};
});
}
然后,您的父組件將有權訪問您提升的子數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.