安装
yarn add react-vant@next
DateTimePicker组件
DateTimePicker默认只支持touch事件,要在桌面端能用,需安装vant touch emulator
为了方便日期格式转换,使用dayjs
yarn add @vant/touch-emulatoryarn add dayjs
注意这里给日历添加了遮罩层
import { DatetimePicker } from 'react-vant'import '@vant/touch-emulator'import dayjs from 'dayjs'// 添加遮罩层const DateTimeWrapper = styled.div`position: absolute;width: 100%;background: rgba(0, 0, 0, 0.3);height: 100%;z-index: 1;.rv-picker {position: absolute;bottom: 0;left: 0;width: 100%;}`function Money() {const [datePickerShow, setDatePickerShow] = useState(false)const [pickedDate, setPickedDate] = useState(dayjs())const [displayDate, setDisplayDate] = useState(dayjs().format('YYYY/MM/DD'))useEffect(() => {setDisplayDate(dayjs(pickedDate).format('YYYY/MM/DD'))}, [pickedDate])const confirmPickedDate = (value: Date) => {setDatePickerShow(!datePickerShow) // 隐藏日期组件需写在前面,否则报错setPickedDate(dayjs(value))}return (<MyLayout scrollTop={9999}>{datePickerShow ? (<DateTimeWrapperonClick={(e) => {// 判断点击的是遮罩层自身if (e.target === e.currentTarget) {setDatePickerShow(false)}}}className="datetimewrapper"><DatetimePickertitle="选择年月日"type="date"minDate={new Date(2020, 0, 1)}maxDate={new Date()}value={new Date()}onCancel={() => setDatePickerShow(false)}onConfirm={(value: Date) => confirmPickedDate(value)}/></DateTimeWrapper>) : ('')}</MyLayout>)}export default Money
Notify组件代替window.alert
import { Notify } from 'react-vant';Notify.show('通知内容');Notify.show({ type: 'primary', message: '通知内容' })// type: 'success' 'warning' 'danger'
Dialog组件代替window.confirm
import { Dialog } from 'react-vant';Dialog.confirm({title: '提示',message: '是否删除该标签?',}).then(() => {const result = deleteTag(tag.id)if (result === 'success') {history.goBack()Notify.show({ type: 'success', message: '删除成功' })}}).catch(() => {console.log('catch')})
自定义样式
@media (min-width: 500px) {.rv-popup--top,.rv-overlay {width: 500px;left: 50%;transform: translateX(-50%);}}
使用 Dialog 和 Field 组件封装弹出输入框组件
import { useTags } from 'hooks/useTags'import React, { useEffect, useRef, useState } from 'react'import { Dialog, Field, FieldInstance } from 'react-vant'type Category = '-' | '+'interface Props {visible: booleansetVisible: (value: boolean) => voidcategory: CategoryaddTag: (type: Category, tag: string) => void}export const Prompt: React.FC<Props> = (props) => {const { visible, setVisible, category, addTag } = propsconst [inputValue, setInputValue] = useState('')const fieldRef = useRef<FieldInstance>(null)useEffect(() => {fieldRef.current?.focus() // 输入框获取焦点}, [visible])return (<Dialogvisible={visible}title="请输入标签名"showCancelButtononConfirm={() => {setVisible(false)const value = inputValuesetInputValue('')console.log(value)addTag(category, value)}}onCancel={() => {setVisible(false)setInputValue('')}}><Fieldref={fieldRef}placeholder="在这里输入标签名"value={inputValue}onChange={setInputValue}/></Dialog>)}
