javascript - 如何通过 reactnavigation v5 将参数从一个屏幕传递到另一个屏幕

标签 javascript reactjs react-native

我有一个问题:这是一个用户列表,我想向任何用户添加约会,所以在用户屏幕上添加约会屏幕上的 PlusButton 发送用户(从用户屏幕的 headerRight 呈现的 PlusButton)。但我不知道如何传递给 AddAppointmentScreen 用户 ID,因为链接到屏幕不是通过按钮,而是通过 react-navigation v5。

这是一个link到我在 github 上的项目

应用程序.js

const HeaderRight = ({ navigation, target }) => {
    return (
        <Button transparent onPress={() => navigation.navigate(target)}>
            <Icon name='plus' type='Entypo' style={{ fontSize: 26 }} />
        </Button>
    )
}


<Stack.Screen
                name='Patient'
                component={PatientScreen}
                options={{
                    title: 'Карта пациента',
                    headerTintColor: '#2A86FF',
                    headerTitleAlign: 'center',
                    headerTitleStyle: {
                        fontWeight: 'bold',
                        fontSize: 20,
                    },
                    headerBackTitleVisible: false,
                    headerRight: () => <HeaderRight navigation={navigation} target={'AddAppointment'} />,
                }}
/>

添加AppointmentScreen.js
import React, { useState } from 'react'
import { Keyboard } from 'react-native'
import { Container, Content, Form, Item, Input, Label, Icon, Text, Button } from 'native-base'
import DateTimePicker from '@react-native-community/datetimepicker'
import styled from 'styled-components/native'

import { appointmentsApi } from '../utils/api'

const AddAppointmentScreen = ({ route, navigation }) => {
    const [values, setValues] = useState({ patientId: route.params?.patientId._id ?? 'defaultValue' })
    const [date, setDate] = useState(new Date())
    const [mode, setMode] = useState('date')
    const [show, setShow] = useState(false)

    console.log(values.patientId)
    //I need to get patientId in this screen to create appointment to THIS user with its ID

    const setFieldValue = (name, value) => {
        setValues({
            ...values,
            [name]: value,
        })
    }

    const handleChange = (name, e) => {
        const text = e.nativeEvent.text
        setFieldValue(name, text)
    }

    const submitHandler = () => {
        appointmentsApi
            .add(values)
            .then(() => {
                navigation.navigate('Patient')
            })
            .catch((e) => {
                alert(e)
            })
        /* alert(JSON.stringify(values)) */
    }

    const formatDate = (date) => {
        var d = new Date(date),
            month = '' + (d.getMonth() + 1),
            day = '' + d.getDate(),
            year = d.getFullYear()

        if (month.length < 2) month = '0' + month
        if (day.length < 2) day = '0' + day

        return [year, month, day].join('-')
    }

    const onChange = (event, selectedDate) => {
        Keyboard.dismiss()
        const currentDate = selectedDate || date
        const date = formatDate(currentDate)
        const time = currentDate.toTimeString().split(' ')[0].slice(0, 5)
        setShow(Platform.OS === 'ios')
        setDate(currentDate)
        setValues({
            ...values,
            ['date']: date,
            ['time']: time,
        })
    }

    const showMode = (currentMode) => {
        show ? setShow(false) : setShow(true)
        setMode(currentMode)
    }

    const showDatepicker = () => {
        Keyboard.dismiss()
        showMode('datetime')
    }

    return (
        <Container>
            <Content style={{ paddingLeft: 20, paddingRight: 20 }}>
                <Form>
                    <Item picker style={{ borderWidth: 0 }} /* floatingLabel */>
                        <Input
                            onChange={handleChange.bind(this, 'dentNumber')}
                            value={values.dentNumber}
                            keyboardType='number-pad'
                            clearButtonMode='while-editing'
                            placeholder='* Номер зуба'
                        />
                    </Item>
                    <Item picker>
                        <Input
                            onChange={handleChange.bind(this, 'diagnosis')}
                            value={values.diagnosis}
                            clearButtonMode='while-editing'
                            placeholder='* Диагноз'
                        />
                    </Item>
                    <Item picker>
                        <Input
                            onChange={handleChange.bind(this, 'description')}
                            value={values.description}
                            multiline
                            clearButtonMode='while-editing'
                            placeholder='Подробное описание или заметка'
                            style={{ paddingTop: 15, paddingBottom: 15 }}
                        />
                    </Item>
                    <Item picker>
                        <Input
                            onChange={handleChange.bind(this, 'price')}
                            value={values.price}
                            keyboardType='number-pad'
                            clearButtonMode='while-editing'
                            placeholder='* Цена'
                        />
                    </Item>

                    <ButtonRN onPress={showDatepicker}>
                        <Text style={{ fontSize: 18, fontWeight: '400' }}>
                            Дата: {formatDate(date)}, время: {date.toTimeString().split(' ')[0].slice(0, 5)}
                        </Text>
                    </ButtonRN>

                    {show && (
                        <DateTimePicker
                            timeZoneOffsetInSeconds={21600}
                            minimumDate={new Date()}
                            value={date}
                            mode={mode}
                            is24Hour={true}
                            display='default'
                            locale='ru-RU'
                            minuteInterval={10}
                            onChange={onChange}
                        />
                    )}

                    <ButtonView>
                        <Button
                            onPress={submitHandler}
                            rounded
                            block
                            iconLeft
                            style={{ backgroundColor: '#84D269' }}
                        >
                            <Icon type='Entypo' name='plus' style={{ color: '#fff' }} />
                            <Text style={{ color: '#fff' }}>Добавить прием</Text>
                        </Button>
                    </ButtonView>
                    <Label style={{ marginTop: 10, fontSize: 16 }}>
                        Поля помеченные звездочкой <TomatoText>*</TomatoText> обязательны для заполнения
                    </Label>
                </Form>
            </Content>
        </Container>
    )
}

const ButtonRN = styled.TouchableOpacity({
    paddingTop: 15,
    paddingLeft: 5,
})

const ButtonView = styled.View({
    marginTop: 15,
})

const TomatoText = styled.Text({
    color: 'tomato',
})

export default AddAppointmentScreen

最佳答案

我没有查看您的代码,但我可以告诉您如何根据您的标题将参数传递到下一个屏幕。

  toNavigate = (user) => {

    this.setState({ isLoading: false },
        () => { this.props.navigation.push('Main', { userData: user }) })
//I am sending user into userData to my Main screen
}

我收到它就像
render(){
 user = this.props.route.params.userData;
 }

如果有任何问题让我知道。

希望能帮助到你!!!

关于javascript - 如何通过 reactnavigation v5 将参数从一个屏幕传递到另一个屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62161319/

相关文章:

javascript - Knockout.js - 在下拉列表中设置属性,而不永久绑定(bind)到模型

javascript - 添加 ajax 来删除对象 - Rails

javascript - 淡入输入图像,淡出输出图像

javascript - 如何更新 Redux + React 中的嵌套对象属性?

android - React Native Android Slider 无法在设备上垂直滑动

javascript - 使用正则表达式替换除了第一次出现的空白子串之外的所有内容

javascript - 使用history.push重置useState

javascript - React.js 中声明式和命令式的区别?

javascript - 将 redux-saga 与 ES6 生成器结合使用与 redux-thunk 与 ES2017 async/await 结合使用的优缺点

css - 如果我可以使用三元运算符来响应原生 CSS?