reactjs - 以编程方式聚焦并选择 react 选择中的值

标签 reactjs styled-components react-select ref

我希望能够以编程方式focus()select()进行react-select。点击下面的添加新品牌:

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

我显然在这里做错了什么,但我无法发现什么。

最佳答案

我认为原因是您必须使用 useRef Hook 的默认值

const brandSelectRef = useRef(null)

关于reactjs - 以编程方式聚焦并选择 react 选择中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61572628/

相关文章:

javascript - 通过从 Blade 接收到的数组 react js循环

reactjs - Keycloak - 保护 Spring Boot 应用程序

reactjs - React select loadOptions 没有在第二次渲染中被调用

javascript - 使用react-select将值传递给状态

javascript - React-Spring错误: 'animated' library from react-spring returns ERROR element type is invalid

javascript - 如何向 react 函数和重新渲染函数添加事件

reactjs - 如何配置 Prettier 来格式化 Styled Components 条件渲染

javascript - 如何将 Prop 传递给样式化的组件

reactjs - 样式化组件文件夹系统

javascript - React-Select onClick 多标签防止打开下拉菜单