简体   繁体   English

在 react-select 中以编程方式聚焦和 select 值

[英]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.currentundefined

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM