我在我的redux商店中存储了一个ref,并使用mapStateToProps公开了需要访问它的组件的ref.
存储的ref看起来像:
ref={node => this.myRefToBePutInReduxGlobalStore = node}
Run Code Online (Sandbox Code Playgroud)
这个参考的正确propType是什么?
Pan*_*olo 46
在OP问题中,它不是需要定义的实际ref prop类型,而是ref指向的结果元素.
在这种情况下,道具类型应该是:
mapStateToProps
(虽然,我会将其重命名为myRefToBePutInReduxGlobalStore: PropTypes.instanceOf(Element)并且同意在redux存储中插入非可序列化数据不是一个好习惯,如Redux FAQ中所述)
注意:跳到答案的底部以评论服务器端用例
另一方面,如果你真的想要强制实际ref的类型,例如转发到另一个组件的ref的prop,你必须允许对象形成的对象myElementToBePutInReduxGlobalStore(在React组件中创建ref 的首选方法,请参阅此处的反应代码{ current: [something] }类型)和类型.
React.createRef()用于使用创建的引用React.useRef()[something] 用于上述问题中使用的回调引用其中给出了以下PropType定义:
function FancyInput({ inputRef }) {
return (
<div className="fancy">
Fancy input
<input ref={inputRef} />
</div>
)
}
FancyInput.propTypes = {
inputRef: ??? // What is the correct prop type here?
}
function App() {
const inputRef = React.useRef()
useEffect(function focusWhenStuffChange() => {
inputRef.current && inputRef.current.focus()
}, [stuff])
return <FancyInput inputRef={inputRef} />
}
Run Code Online (Sandbox Code Playgroud)
注意服务器端渲染
如果您的代码类型的代码在服务器上运行,除非您已经填充DOM环境,PropTypes.func否则将在NodeJS中未定义.您可以使用以下填充程序来支持它:
refProp: PropTypes.oneOfType([
// Either a function
PropTypes.func,
// Or the instance of a DOM native element (see the note about SSR)
PropTypes.shape({ current: PropTypes.instanceOf(Element) })
])
Run Code Online (Sandbox Code Playgroud)
在评论中查看更多详情(感谢@Rahul Sagore)
编辑:添加@Ferenk Kamras提到的对象PropType的特定形状
svn*_*vnm 18
与@Pandaiolo 的帖子非常相似,
PropTypes.elementType 现在已添加
forwardedRef: PropTypes.oneOfType([
PropTypes.func,
PropTypes.shape({ current: PropTypes.elementType })
]),
Run Code Online (Sandbox Code Playgroud)
如果使用 PropTypes >= 15.7.0PropTypes.elementType已于 2019 年 2 月 10 日添加到此 PR 中
小智 8
我只检查首选方式,因为PropType.object不是很有价值,我最终使用了这个:
PropTypes.shape({ current: PropTypes.instanceOf(Element) })
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16561 次 |
| 最近记录: |