问题描述
我有一个问题:这是一个用户列表,我想向任何用户添加约会,因此在用户屏幕上,添加约会屏幕上的 PlusButton 发送用户(从用户屏幕的 headerRight 呈现的 PlusButton).但我不知道如何传递给 AddAppointmentScreen 用户 ID,因为不是通过按钮链接到屏幕,而是通过 react-navigation v5.
I have an issue: thre is a list of users, and I want to add appointment to any user, so on user screen a PlusButton sending user on the add appointment screen (the PlusButton rendered from headerRight of the user screen). BUT I dont know how to pass to AddAppointmentScreen users id, because link to screen not via button, its via react-navigation v5.
这是我在 github 上的项目的链接
here is a link to my project on github
App.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
AddAppointmentScreen.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
推荐答案
我是这样解决的:
- 在 StackScreen 中获取参数 - 您需要传递给选项路由和导航,然后您可以获得如下所示的路由参数:
<Stack.Screen
name='Patient'
component={PatientScreen}
options={({ route, navigation }) => {
return {
title: 'Карта пациента',
headerTintColor: '#2A86FF',
headerTitleAlign: 'center',
headerTitleStyle: {
fontWeight: 'bold',
fontSize: 20,
},
headerBackTitleVisible: false,
headerRight: () => (
<HeaderRight target={'AddAppointment'} patientId={route.params.patientId} />
),
}
}}
/>
- 然后我在 HeaderRight 组件中获得了 PatientId 并将其传递到新屏幕,第二个参数带有这样的导航(当然可以选择不使用此组件并将其从 Stack.Screen 传递,但我将其传递给了我自己的目的):
const HeaderRight = ({ patientId, target }) => {
const navigation = useNavigation()
return (
<Button transparent onPress={() => navigation.navigate(target, { patientId })}>
<Icon name='plus' type='Entypo' style={{ fontSize: 26 }} />
</Button>
)
}
- 我在第三个屏幕中获得了patientId,如下所示:
patientId: route.params?.patientId ??'',
这篇关于如何通过 reactnavigation v5 将参数从一个屏幕传递到另一个屏幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!