简体   繁体   中英

How to open a Component in an onPress call?

So basically I have a Screen in my app that has a Button in it and this button should open a Modal that is also a selfmade component in the same screen js file.

I am setting the state visible in the screen and the button has an onPress handler that toggles the visible state (false/true).

I dont know how to display my own modalComponent when the button is clicked.

btw using react-native-modal

Own modal component:

class PhasenModal extends Component {
  render() {
    return (
      <View>
        <Modal isVisible={this.props.visible}>
          <View style={{ flex: 1 }}>
            <Text>I am a modal</Text>
          </View>
        </Modal>
      </View>
    );
  }
}

In my ScreenView :

<Button
  buttonStyle={styles.phaseButton}
  title="Choose"
  onPress={() => this.phasenModalHandler()}
/>

The onPress fnct:

phasenModalHandler() {
  this.setState({ visible: !this.state.visible });
  if (this.state.visible) {
    return <PhasenModal visible={this.state.visible} />;
  } else {
    return;
  }
}

I expect the button to show the Modal but it doesnt show anything , the state gets toggled correctly tho it switched from false to true.

I guess my onPress fctn is wrong becaus I dont know how to render the component.

Thank you in advance.

What you return from your event handler will not be rendered, so you could instead use the visible value in your state to conditionally render the PhasenModal component.

class ScreenView extends Component {
  state = {
    visible: false
  };

  phasenModalHandler = () => {
    this.setState(({ visible }) => ({ visible: !visible }));
  };

  render() {
    return (
      <>
        <Button
          buttonStyle={styles.phaseButton}
          title="Choose"
          onPress={this.phasenModalHandler}
        />
        {this.state.visible && <PhasenModal />}
      </>
    );
  }
}

class PhasenModal extends Component {
  render() {
    return (
      <View>
        <Modal isVisible>
          <View style={{ flex: 1 }}>
            <Text>I am a modal</Text>
          </View>
        </Modal>
      </View>
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM