React最终形成Prime React的动态下降



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

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' }}
/>
)
}

相关内容

  • 没有找到相关文章