使用 Prime React 响应最终表单动态下拉列表

React Final Form Dynamic Dropdown with Prime React

我正在尝试使用 PrimeReact 库中的 DropDown 初始化动态用户列表。我能够加载它,即使我不确定它是否是正确的方式。我可以 select 一个用户,但无法将其传递给表单。我也不确定我是否应该 select 没有状态的用户。我对它们之间如何相互作用感到有点困惑。如果我能得到一些指导,那将非常有帮助。

import { useState, useEffect, useContext } from 'react'
import { Form, Field } from 'react-final-form'
import { Panel } from 'primereact/panel'
import { Dropdown, DropdownProps } from 'primereact/dropdown'
import { Button } from 'primereact/button'

import { api } from '../services' //Axios instance

export interface IUser {
    id: number
    firstName: string
    lastName: string
  }

const selectedUserItemTemplate = (option: IUser) => {
  return <span>{`${option.lastName} ${option.firstName}`}</span>
}

const selectedUserValueTemplate = (
  option: IUser,
  { placeholder }: DropdownProps
) => {
  return option ? (
    <span>{`${option.lastName} ${option.firstName}`}</span>
  ) : (
    <span>{placeholder}</span>
  )
}

const DropDownAdaptater = ({ input, meta, hintText, data, ...rest }: any) => {
  const [selectedUser, setSelectedUser] = useState(undefined)
  const [users, setUsers] = useState<IUser[]>([])
  useEffect(() => {
    const fetchUsers = async () => {
      const { data } = await api.get<IUser[]>('/users')
      setUsers(data)
    }
    fetchUsers()
  }, [])

  console.log(input.value) //Empty -> the form does not update

  return (
    <Dropdown
      {...input}
      value={selectedUser}
      options={users}
      onChange={(e) => setSelectedUser(e.target.value)}
      itemTemplate={selectedUserItemTemplate}
      valueTemplate={selectedUserValueTemplate}
      optionLabel="optionLabel"
      placeholder={hintText}
      style={{ marginRight: '1rem', width: '240px' }}
    />
  )
}

export const Login: React.FC = () => {
  const onSubmitAuthForm = () => {
    console.log('submit')
  }

  return (
    <Panel header="Login">
      <Form onSubmit={onSubmitAuthForm}>
        {({ handleSubmit, form, submitting, pristine, values }) => {
          console.log('values FORM', values) // -----> Empty
          return (
            <form onSubmit={handleSubmit}>
              <h5>Select a user</h5>
              <Field
                name="userName"
                component={DropDownAdaptater}
                hintText="Select a user"
              />
              <Button label="Login" />
            </form>
          )
        }}
      </Form>
    </Panel>
  )
}

尝试更新您自己的值。

看这里的例子

const DropDownAdaptater = ({ input, meta, hintText, data, ...rest }: any) => {
  const [selectedUser, setSelectedUser] = useState(undefined)
  const [users, setUsers] = useState<IUser[]>([])
  useEffect(() => {
    const fetchUsers = async () => {
      const { data } = await api.get<IUser[]>('/users')
      setUsers(data)
    }
    fetchUsers()
  }, [])

  useEffect(()=>{
   // update the input value, when selected
   note: it must be a single value and not an object
      input.value= selectedUser.userName; 
  },[selectedUser])

  return (
    <Dropdown
      {...input}
      value={selectedUser}
      options={users}
      onChange={(e) => setSelectedUser(e.target.value)}
      itemTemplate={selectedUserItemTemplate}
      valueTemplate={selectedUserValueTemplate}
      optionLabel="optionLabel"
      placeholder={hintText}
      style={{ marginRight: '1rem', width: '240px' }}
    />
  )
}