React:创建组合框

问题描述 投票:0回答:1

这里的学生,尝试使用 Laravel、React 和 Inertia 为我的论文创建一个应用程序。

我正在尝试创建一个简单的、可重用的 Combobox 组件。它需要有一个 id HTML 属性,并且需要包含一个 id 作为值,以便我可以在 Laravel 控制器中使用两者。

这就是我所拥有的。问题是handleSelect 函数的大部分行都不起作用。 (标有“不会发生”。)

import { useState } from "react"

export default function Combobox ({}) {
    const [input, setInput] = useState('')
    const [returnValue, setReturnValue] = useState ('')
    const [showUl, setShowUl] = useState(false)

    //TURN INTO PROPS
        const title = 'test'
        const array = [
            { id: 1, name: 'eins' },
            { id: 2, name: 'zwei' },
            { id: 3, name: 'polizei' },
        ]
    //end of props

    const filteredArray = (
        input
        ? array.filter(item => item.name.toLowerCase().includes(input.toLowerCase()))
        : array
    )

    const handleSelect = (name, id) => {
        setInput(name) // does not happen.
        setReturnValue(id) // does not happen.
        setShowUl(false)
        console.log(`input is now ${input}`) // does not happen.
    }

    // const handleBlur = () => {
    //     setShowUl(false)
    //     const found = array.find(input)
    //     if (found) {
    //         setReturnValue(found.id)
    //         setInput(found.name)
    //     } else {
    //         alert('No matches found.')
    //         setReturnValue('')
    //     }
    // }

    return (
        <>
            <input
                id={`${title}_input`}
                type="text"
                placeholder='klik of typ om te kiezen'
                value={input}
                onChange={e => {setInput(e.target.value)}}
                onFocus={() => {setShowUl(true)}}
                onBlur={() => {setShowUl(false)}} //insert handleBlur here
            />
            <input
                id={`${title}_id`} //$request->{title}_id will be used in a Laravel controller.
                type="hidden"
                value={returnValue}
            />
            {showUl &&
                <ul>
                    {filteredArray.map(item => (
                        <li
                            key={item.id}
                            onClick={() => handleSelect(item.name, item.id)}
                        >{item.name}</li>
                    ))}
                </ul>
            }
        </>
    )
}

当用户从 ul 中选择一个项目时,我期望:

  • 可见输入 {title}_input 包含 item.name
  • 隐藏的 {title}_id 包含 item.id
  • 关闭

我知道我还需要涵盖用户可能在不单击 的情况下键入整个 item.name 的可能性。我打算通过调用handleBlur onBlur来解决这个问题。我需要先解决handleSelect函数的问题。

提前致谢。

reactjs combobox
1个回答
0
投票

试试这个

 onClick={() => this.handleSelect(item.name, item.id)}

onClick={handleSelect(item.name, item.id)}



   
© www.soinside.com 2019 - 2024. All rights reserved.