簡體   English   中英

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

[英]Programmatically focus and select value in react-select

我希望能夠以編程方式focus()select()一個react-select 點擊下方的Add 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

我顯然在這里做錯了什么,但我看不出是什么。

我認為原因是你必須為你的useRef鈎子使用默認值

const brandSelectRef = useRef(null)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM