[英]Programmatically focus and select value in react-select
我希望能夠以編程方式focus()
和select()
一個react-select
。 點擊下方的Add new brand
:
應該呈現如下內容:
這是我到目前為止所擁有的。
我的Select
組件包含在React.forwardRef
中:
const Select = React.forwardRef((props, ref) => {
return (
<Creatable ref={ref} {...props} />
)
})
這樣我就可以使用styled-components
對其進行樣式設置,並且仍然對其輸入有一個ref
,如下所示:
const BrandSelect = styled(Select)`...`
const Button = styled.button`...`
const MyComponent = () => {
const brandSelectRef = useRef()
const [newBrand, setNewBrand] = useState(false)
const handleAddBrand = () => {
setNewBrand(true)
console.log(brandSelectRef.current)
if (brandSelectRef && brandSelectRef.current) {
brandSelectRef.current.focus()
brandSelectRef.current.select()
}
}
return (
<BrandSelect
creatable
openMenuOnFocus
ref={brandSelectRef}
defaultInputValue={newBrand ? '...' : undefined}
// ...other required react-select props
/>
<Button onClick={handleAddBrand}>Add new brand</Button>
)
}
但是,問題是上面的代碼不起作用,即react-select
永遠不會得到關注。 此外,日志brandSelectRef.current
是undefined
。
我顯然在這里做錯了什么,但我看不出是什么。
我認為原因是你必須為你的useRef
鈎子使用默認值
const brandSelectRef = useRef(null)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.