首页 > 解决方案 > 在 react-select 中以编程方式聚焦和选择值

问题描述

我希望能够以编程方式focus()和. 点击下方:select()react-selectAdd 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.currentundefined.

我显然在这里做错了什么,但我看不出是什么。

标签: reactjsstyled-componentsreact-selectref

解决方案


我认为原因是你必须为你的useRef钩子使用默认值

const brandSelectRef = useRef(null)

推荐阅读