【问题标题】:How to close a component like modal with React Native?如何使用 React Native 关闭像 modal 这样的组件?
【发布时间】:2021-02-08 05:47:01
【问题描述】:

我创建了一个类索引,它像模态一样调用组件“TelaAdd”。模态打开但我不知道如何关闭它。我尝试使用 setShow 但不起作用。 在 Modal 中有一个 Icon 之前正在关闭它,但是我不得不更改创建类组件的代码并且它停止工作。我想在 Modal 中按下图标“IconVoltar”并关闭它。

索引.js

import  TelaAdd  from  ' ./AddHospital/Modal '


class Index extends Component 

{

constructor (props) {

    super(props)   
    this.state = {
        listaFirebase: [],
        showModal: false,
        search: ''              
    }}

   openModal(value) {

     this.setState({
        showModal: value })}


 render () {    
    return (            
        <Container>
          <TouchableOpacity style={styles.addButton}
            activeOpacity={0.7}
            onPress={() => this.openModal(true)}>

                <Icon name="plus" size={20} color='#f2f2f2' />
          </TouchableOpacity>

          <TelaAdd               
                show={this.state.showModal}
                setShow(that's right?) />
        </Container>

另一个文件 模态.js

export default ({ show, setShow })  =>  {

   const onCancel = () => 
    {
       setShow(false) 
    }

       return (
        <ModalHead transparent={ true } visible = { show }             
         animationType='slide' >
           <ModalArea>
                    <ModalBody>
                        <Voltar onPress = { (  => onCancel () } >
                            <IconVoltar width="30" height="30" fill="#000" />
                        </Voltar>
                   </ModalBody>
           </ModalArea>
       </ModalHead>"
}

【问题讨论】:

  • 当你将 setShow 传递给 TelaAdd 组件时,你是在写 setShow={setShow} 还是只是 setShow?因为您似乎只是根据上面的内容编写 setShow

标签: java reactjs react-native native


【解决方案1】:

您可能需要将this 绑定到打开的模式处理程序。

这可以在构造函数中完成

constructor (props) {
  super(props)   ;
  this.state = {
    listaFirebase: [],
    showModal: false,
    search: ''              
  };

  this.openModal = this.openModal.bind(this);
}

或者可以使用箭头函数来完成

openModal = (value) => {
  this.setState({ showModal: value });
};

您似乎也没有正确地将 setShow 回调传递给模式,它看起来应该openModal 回调。

render () {
  return (
    <Container>
      <TouchableOpacity style={styles.addButton}
        activeOpacity={0.7}
        onPress={() => this.openModal(true)}
      >
        <Icon name="plus" size={20} color='#f2f2f2' />
      </TouchableOpacity>
      <TelaAdd               
        show={this.state.showModal}
        setShow={this.openModal} // <-- pass this.openModal as setShow
      />
    </Container>

【讨论】:

  • @Samuel 太好了!请接受答案,以便其他人知道它已解决。如果觉得有帮助,也点赞。干杯。
猜你喜欢
  • 2019-06-26
  • 2021-03-23
  • 1970-01-01
  • 2019-08-09
  • 1970-01-01
  • 2018-09-04
  • 1970-01-01
  • 1970-01-01
  • 2020-11-16
相关资源
最近更新 更多