我希望能够通过编程 focus()
和 select()
a 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)