javascript 将react js中的react选择值传递给firebase

ecr0jaav  于 2023-02-18  发布在  Java
关注(0)|答案(1)|浏览(108)

我使用react-value来添加下拉选项,这些选项将在单击oncall函数时出现,并传入一些静态值,这些值是我硬编码的,如以下代码所示:

import React, {useMemo, useState} from "react"
import Select from 'react-select'
import { db } from '../firebase/config'
import { collection, addDoc } from 'firebase/firestore'
import { useNavigate } from 'react-router-dom'

export default function JobApplication() {

const timeline = [
        { value: 'one-week', label: 'In one week'},
        { value: 'two-weeks', label: 'In two weeks'},
        { value: 'one-month', label: 'Within a month'},
        { value: 'more', label: 'More than a month'},
    ]

我在const时间轴中硬编码的值然后被传递到以下代码中:

<div className="flex flex-col mt-12 items-start">
                <label className="mb-3 text-sm leading-none text-gray-800">When can you start?</label>
                <Select required key={timeline} options={timeline} onChange={changeHandler} />
        </div>

因此,我将Select调用封装在form中,并传入我通过以下代码创建的函数onSubmit={handleSubmit}:

const handleSubmit = async (e) => {
        e.preventDefault();

        navigate('/home')

用户做出选择后,是否有方法将硬编码选定值从时间轴传递到Firebase?

kb5ga3dv

kb5ga3dv1#

你可以使用UseState钩子来存储selectedTimeline,然后创建一个changeHandler,然后更新handleSubmit

const [selectedTimeline, setSelectedTimeline] = useState(null);

const changeHandler = (selectedOption) => {
  setSelectedTimeline(selectedOption.value);
};

const handleSubmit = async (e) => {
  e.preventDefault();

  const docRef = await addDoc(collection(db, "jobApplications"), {
    timeline: selectedTimeline,
    // u can  other form data 
  });

  navigate('/home');
};

相关问题