以编程方式集中并选择反应选择中的值

时间:2020-05-03 10:01:04

标签: reactjs styled-components react-select ref

我希望能够以编程方式focus()select()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

我在这里显然做错了,但是我找不到。

1 个答案:

答案 0 :(得分:0)

我认为原因是您必须为useRef挂钩使用默认值

const brandSelectRef = useRef(null)