Return a custom Alert in react native

时间:2017-06-23 03:25:09

标签: react-native

I am trying to launch a custom Alert component from an onPress call from Touchable Highlight. I have been unable to get this to work, I have tried console logging from inside the custom Alert component render function and the code doesn't run to this point because I am unable to see this log. What is confusing me is that when I tested this with the React-Native Alert this did run and show that Alert. I would appreciate some help understanding what I am doing wrong here because I feel I am misunderstanding something. I have used the Alert component before and it works fine but in these instances it has only been when i have called the Alert directly not from onPress.

onPress() {
  return (
    <Alert
      message={i18n('alerts.improvements')}
    />
  )
}

render() {
  return (
    <TouchableHighlight onPress={() => this.onPress.bind(this)}>
      <Text>Test Text</Text>
    </TouchableHighlight>
  )
}

The Alert Component with the console log that doesn't get hit:

class Alert extends Component{
  props: {
    message: string
  }

  state = {
   modalVisible: false,
  }

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

  render() {
    console.log('modal')
    return (
      <Modal
        animationStyle='fade'
        transparent={true}
        visible={!this.state.modalVisible}
        onRequestClose={() => {}}
      >
        <View style={styles.container}>
          <Text style={styles.text}>{this.props.message}</Text>
        </View>
      </Modal>
    )
  }
}

export default Alert

1 个答案:

答案 0 :(得分:1)

您可以将默认值onPress放在false中,而不是将其称为render。然后为您的组件添加一个支柱,以管理它的可见性。

例如:

in component:
    <Modal
            animationType={'fade'}
            transparent={true}
            visible={this.props.isOpen}
            onRequestClose={this.props.actionClose}>

while calling:
<ModalBox
            isOpen={this.props.isOpen}

我有isOpen道具可见度