useState 到 hide/show 模态反应本机

useState to hide/show modal in react native

我想根据 useState 更新在应用程序的任何位置调整我的登录屏幕。我有一个屏幕,其中有一个按钮:

    const [needLogin, setNeedLogin] = useState(false);

    return (
...
            <TouchableOpacity onPress={() => {
                setNeedLogin(true) //This is hardcoded I'll set this value later via an  API response but for now, I just want to show the screen every time it's pressed so hard coding it to true
            }}>
                <Text>Ask Your Question</Text>
            </TouchableOpacity >
            
            {needLogin && <AuthScreen />}
...
    )

现在 AuthScreen 编码为:

    const [showModal, setShowModal] = useState(true);

    return (
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
            <Modal visible={showModal} animationType={'slide'} >
                <View style={styles.modal}>
                    <View style={styles.modalContainer}>
                            <View style={styles.header}>
                                <TouchableOpacity onPress={() => { setShowModal(false) }}>
                                    <Image source={require('../assets/close-icon.png')} />
                                </TouchableOpacity>
                            </View>
                            <LoginForm />
                    </View>
                </View>
            </Modal >
        </View >
    );

这个逻辑工作一次意味着,我将点击 Ask Question 按钮,它会显示 AuthScreen 然后当我点击 close-icon 时它会关闭它但是如果我再次点击 Ask Question 它不会显示 AuthScreen.

您的 AuthScreen 第二次没有显示的原因是您从未将 needLogin 状态设置回 false。所以下次您尝试将其设置为 true 时,它​​不会导致重新渲染。

更好的处理方法是不维护 AuthScreen 的单独状态,而是从 props 派生它,并提供一种更新父级状态的方法

    const [needLogin, setNeedLogin] = useState(false);

    return (
    ...
            <TouchableOpacity onPress={() => {
                setNeedLogin(true) //This is hardcoded I'll set this value later via an  API response but for now, I just want to show the screen every time it's pressed so hard coding it to true
            }}>
                <Text>Ask Your Question</Text>
            </TouchableOpacity >
            
            <AuthScreen open={needLogin} closeModal={() => setNeedLogin(false)}/>
       ...
    )

const { open, closeModal } = props;

return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Modal visible={open} animationType={'slide'} >
            <View style={styles.modal}>
                <View style={styles.modalContainer}>
                        <View style={styles.header}>
                            <TouchableOpacity onPress={() => { closeModal() }}>
                                <Image source={require('../assets/close-icon.png')} />
                            </TouchableOpacity>
                        </View>
                        <LoginForm />
                </View>
            </View>
        </Modal >
    </View >
);