[英]Programmatically focus and select value in react-select
I want to be able to programmatically focus()
and select()
a react-select
.我希望能够以编程方式
focus()
和select()
一个react-select
。 Clicking on Add new brand
below:点击下方的
Add new brand
:
should render something like this:应该呈现如下内容:
Here's what I have so far.这是我到目前为止所拥有的。
My Select
component is wrapped in React.forwardRef
:我的
Select
组件包含在React.forwardRef
中:
const Select = React.forwardRef((props, ref) => {
return (
<Creatable ref={ref} {...props} />
)
})
so that I can style it with styled-components
and still have a ref
to its input, like so:这样我就可以使用
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>
)
}
The problem is, though, that the above code doesn't work, ie react-select
never gets focused.但是,问题是上面的代码不起作用,即
react-select
永远不会得到关注。 Also, the log brandSelectRef.current
is undefined
.此外,日志
brandSelectRef.current
是undefined
。
I'm clearly doing something wrong here, but I can't spot what.我显然在这里做错了什么,但我看不出是什么。
I think the cause is that you have to use default value for your useRef
hook我认为原因是你必须为你的
useRef
钩子使用默认值
const brandSelectRef = useRef(null)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.