当子组件涉及时,React-native模态组件不会回滚

时间:2017-08-19 21:03:11

标签: javascript react-native components

当我按下提交按钮时,模态会向上滑动,但是当我按下“隐藏模态”时,它不会回滚到原点。我在onPress回调后控制台登录ChildScreen.js文件,我得到:

对象{   “modalVisible”:false, }

这意味着模态必须回滚到其原始位置,但这不会发生!有人知道为什么吗?注意:当我不导入!

时,模态完全有效

ParentScreen.js

import React from "react";
import { View, Text, Modal } from "react-native";
import { Button } from 'react-native-elements';
import ChildScreen from './ChildScreen';

export default class ParentScreen extends React.Component {
  state = {
    modalVisible: false
  }

  setModalVisible(visible) {
    this.setState({ modalVisible: visible });
  }
  _onPress() {
    this.setModalVisible(true);
  }

  render() {
    return (
      <View style={{ flex: 1 }}>
        <Modal
          animationType={"slide"}
          transparent={false}
          visible={this.state.modalVisible}
          onRequestClose={() => { alert("Modal has been closed.") }}
        >
          <View style={{ marginTop: 22 }}>
            <ChildScreen />
          </View>
        </Modal>
        <View
          style={{
            position: 'absolute', bottom: 30, left: 0, right: 0, justifyContent: 'center',
          }}
        >
          <Button
            onPress={this._onPress.bind(this)}
            title='SUBMIT' />
        </View>
      </View>
    );
  }
}

ChildScreen.js

import React, { Component } from 'react';
import { View, Text, TouchableHighlight } from 'react-native';


class ChildScreen extends Component {
  state = {
    modalVisible: true
  }

  setModalVisible(visible) {
    this.setState({ modalVisible: visible });
  }
  render() {
    return (
      <View>
        <Text>ChildScreen</Text>
        <TouchableHighlight onPress={() => {
          this.setModalVisible(this.state.modalVisible = false)
          console.log(this.state)
        }}>
          <Text>Hide Modal</Text>
        </TouchableHighlight>
      </View>
    );
  }
}

export default ChildScreen;

1 个答案:

答案 0 :(得分:0)

我向<ChildScreen />组件添加了一个名为隐藏的回调,例如:

<ChildScreen
   hide={this.onModalChange}
/>

并称之为:

<TouchableHighlight onPress={this.props.hide}>
   <Text>Hide Modal</Text>
</TouchableHighlight>

我将状态管理更改为 redux ,一切正常。