在react-select中进行程序化的聚焦和选值。

问题描述 投票:0回答:1

我希望能够通过编程 focus()select() a react-select. 点击 Add new brand 下面。

enter image description here

应该是这样的

enter image description here

这是我目前掌握的情况

我的 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.

很明显,我在这里做错了什么,但我不能确定是什么。

reactjs styled-components react-select ref
1个回答
0
投票

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

const brandSelectRef = useRef(null)
© www.soinside.com 2019 - 2024. All rights reserved.