reactjs - 在 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.current
是undefined
.
我显然在这里做错了什么,但我看不出是什么。
解决方案
我认为原因是你必须为你的useRef
钩子使用默认值
const brandSelectRef = useRef(null)
推荐阅读
- kubernetes - 添加新的 kubernetes master 时出现未经授权的问题
- dns - dnsmasq 可以按指定顺序返回记录吗?
- version-control - Zerobrane 的版本控制
- ecmascript-6 - VSCode“转到定义”:如何显示未编译的 ES6 文件?
- java - 如何以 UTF-8 获取用户输入?
- ios - iOS 12.1.2 branch.io 通用链接打开应用程序,但没有数据存在
- powershell - 并行 Ping 数千台机器,将结果保存到阵列
- excel - 在数据验证中使用“IF”语句和空单元格的问题
- ruby - 用猴子补丁对象以更自然的方式测试元素是否在数组中是一个坏主意吗?
- ios - 带有 xib 的自定义 UIView 中的 UIImageView 出口为零