React中ref的正确proptype是什么?

dan*_*y74 53 reactjs

我在我的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] }类型)和类型.

  1. 对象形状:React.createRef()用于使用创建的引用React.useRef()
  2. [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的特定形状

  • 它使`Element` 未在服务器端渲染中定义。有什么解决办法吗? (3认同)

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 中

  • 最后,“elementType”对我不起作用,所以我实际上在沙箱中测试了不同类型组件上的一堆 prop 类型,这些组件可以由 ref 指向。结果如下:https://codesandbox.io/s/loving-benz-w6fbh。我不确定我是否涵盖了所有可能性,但 DOM 元素的正确 proptype 似乎是 `instanceOf(Element)` (或 `object`),对于类来说它是 `instanceOf(Component)` (或 `object`) ),对于使用“useImperativeHandle”的功能组件的特定用例,它是“object”。想法? (2认同)

小智 8

我只检查首选方式,因为PropType.object不是很有价值,我最终使用了这个:

PropTypes.shape({ current: PropTypes.instanceOf(Element) })
Run Code Online (Sandbox Code Playgroud)