【问题标题】:How to render Alert Component conditionally in react native如何在本机反应中有条件地呈现警报组件
【发布时间】:2019-08-13 02:05:31
【问题描述】:

我正在尝试自定义警报组件。为此,我在 render() 方法中 将 Alert 包装在 AlerBoxContainer 类中(放置在 alertbox-container.tsx 文件中)。我通过使用道具切换来渲染它。

方法-1:如果条件为真则直接返回Alert组件,如果条件为假则返回null。

这在 alertbox-container.tsx 文件中:

import * as React from "react";
import { Alert} from "react-native";
import { connect } from "react-redux";
import { Dispatch } from "redux";
import { State } from "../../../../store/reducer";
import * as constants from "../../constants";
import * as selectors from "../../selectors";
import { AlertBox, AlertBoxContainerProps } from "./alertbox";

interface AlertBoxState {
    showAlert: boolean;
    blurred: boolean;
    appState: any;
}

class AlertBoxContainer extends React.Component<AlertBoxContainerProps, AlertBoxState> {
    constructor(props) {
        super(props);
}

render() {
    return this.props.isAlertVisible ?
        Alert.alert(constants.ALERT_HEADER, constants.ALERT_MESSAGE, [
            { text: constants.CANCEL_TEXT, onPress: () => this.props.onCancel() },
            { text: constants.EXIT_TEXT, onPress: () => this.props.onExit() }
        ])
        :  null;
}
}

const mapStateToProps = (state: State): AlertBoxContainerProps => ({
    isAlertVisible: selectors.getIsAlertVisible(state)
});

const mapDispatchToProps = (dispatch: Dispatch<core.features.workplace.Action>): AlertBoxContainerProps => ({
    toggleAlertVisible: () => dispatch(core.features.workplace.toggleAlertVisible())
});

export default connect<any, AlertBoxContainerProps, AlertBoxContainerProps>(
    mapStateToProps,
    mapDispatchToProps
)(AlertBoxContainer);

当我尝试上面的代码时,我得到了错误:

“AlertBoxContainer”类型中的属性“render”不能分配给基类型“Component”中的相同属性。 类型 '() => void' 不可分配给类型 '() => ReactNode'。 类型 'void' 不可分配给类型 'ReactNode'.ts(2416)

我也尝试了以下方式:

接近 - 2:

在 alertbox-container.tsx 中:

 render() {
return (
    <AlertBox
        isAlertVisible={this.props.isAlertVisible}
        onCancel={this.props.onCancel}
        onExit={this.props.onExit}
    />
);
}

在 alertbox.tsx 文件中:

import { Alert, View } from "react-native";
import * as constants from "../../constants";
export interface AlertBoxContainerProps {
    isAlertVisible?: boolean;
    toggleAlertVisible?: () => any;
    navigation?: any;
    hardwareBackPress?: () => any;
    onExit?: () => any;
    onCancel?: () => any;
}

export const AlertBox = (props: AlertBoxContainerProps) => {
    return props.isAlertVisible
    ? (
        Alert.alert(constants.ALERT_HEADER, constants.ALERT_MESSAGE, [
            { text: constants.CANCEL_TEXT, onPress: () => props.onCancel() },
            { text: constants.EXIT_TEXT, onPress: () => props.onExit() }
        ])
    )
    : null; 
};

当我尝试这段代码时,我得到了错误:“JSX element type 'void' is not a constructor function for JSX elements.ts(2605)”

我怎样才能摆脱这些错误并呈现警报框?

当我尝试使用第二种方法并通过修改代码时,我能够使用以下代码呈现警报:

方法-3:

在 alertbox.tsx 中:

export const AlertBox = (props: AlertBoxContainerProps) => {
return (
    <View>
        {}
        {props.isAlertVisible
            ? Alert.alert(constants.ALERT_HEADER, constants.ALERT_MESSAGE, [
                  { text: constants.CANCEL_TEXT, onPress: () => props.onCancel() },
                  { text: constants.EXIT_TEXT, onPress: () => props.onExit() }
              ])
            : null}
    </View>
);

};

但是代码的语法很奇怪,我需要在视图中放置空的“{}”,否则我会收到错误:

" 类型 'void' 不可分配给类型 'ReactNode'.ts(2322) index.d.ts(725, 39): 预期的类型来自属性 'children',在此处声明类型为 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly>' "。

【问题讨论】:

    标签: javascript reactjs typescript react-native


    【解决方案1】:
     <View>
        {}
        {props.isAlertVisible
            && Alert.alert(constants.ALERT_HEADER, constants.ALERT_MESSAGE, [
                  { text: constants.CANCEL_TEXT, onPress: () => props.onCancel() },
                  { text: constants.EXIT_TEXT, onPress: () => props.onExit() }
              ])
            }
    </View>
    

    如果 null 导致了问题,那么您可以做一个短路 希望对您有所帮助!

    【讨论】:

    • 请查看我尝试的最后一种方法...与您的建议相同。在那里我没有遇到任何关于 null 的问题,我可以渲染警报框,但我想删除 组件中的空“{}”符号,因为它在语法上很奇怪。
    【解决方案2】:

    这个问题是Alert.alert()不是一个组件,它是一个函数(调用alert()方法)。 render 函数必须传递 Component,这就是您收到错误的原因。

    Alert.alert() 易于使用且得心应手。它根本不需要在render 方法中工作,事实上它甚至不需要在Component 中工作。您需要做的就是在您想要它出现时调用它。例如,您可以通过以下方式在按下按钮时发出警报:

    class Example extends Component<*, *> {
      
      callAlert = () => {
        Alert.alert(
          “Alert title”,
          “Alert explanation”,
          [
            {
              text: “Yes”,
              onPress: () => console.log(“Yes pressed”),
            },
            {
              text: “No”,
              onPress: () => console.log('No Pressed'),
            },
          ],
          { cancelable: false }
        );
      };
    
      render() {
        return (
          <TouchableOpacity onPress={this.callAlert}>
            <Text>
              Alert Button
            </Text>
          </TouchableOpacity>
        );
      }
    }
    

    在你的情况下,每当你切换你的道具时,调用警报,一切都应该是桃色的!

    【讨论】:

      猜你喜欢
      • 2018-03-09
      • 2021-04-18
      • 1970-01-01
      • 2021-03-18
      • 1970-01-01
      • 2020-01-18
      • 1970-01-01
      • 1970-01-01
      • 2019-09-24
      相关资源
      最近更新 更多