我在 React 中有一个自定义组件,我希望能够保存一个 ref (即,它应该有
ref
作为它的 props 之一)。 (如果我们想将其用作 ToolTip
组件的子组件,这是必需的。)我们使用 Material-UI 作为组件,使用 PropTypes 进行 prop 验证,我们的代码是 JavaScript。该组件的代码很像以下:
import { FormControlLabel, Switch } from '@mui/material'
import PropTypes from 'prop-types'
function LabeledSwitch({ label, checked, onChange, required, ...otherProps }) {
return (
<FormControlLabel
control={<Switch {...otherProps} />}
label={label}
checked={checked}
onChange={onChange}
required={required}
/>
)
}
LabeledSwitch.propTypes = {
label: PropTypes.string.isRequired,
checked: PropTypes.bool,
onChange: PropTypes.func,
required: PropTypes.bool
}
LabeledSwitch.defaultProps = {
checked: false,
onChange: null,
required: false
}
export default LabeledSwitch
我想将
ref
添加到组件的属性列表中,并将 FormControlLabel
的控制属性设置为:
control={<Switch {...otherProps} inputRef={ref} />}
并且
ref
的默认值为 null
。我的问题是我不能简单地添加
ref: PropTypes.ref,
进入
LabeledSwitch.propTypes
列表,因为 ref
不是 PropTypes 识别的类型。我该如何指定 ref
属性实际上是一个 ref ?或者,我是否简单地指定它是一个 element
(对我来说,这听起来不对)?
Ref 是一个带有属性
current
的对象。所以应该是这样
ref: PropTypes.object