与 `PropTypes.element` 对应的 `defaultProp` 的正确值是多少? [英] What is the correct value for a `defaultProp` that corresponds to a `PropTypes.element`?

查看:44
本文介绍了与 `PropTypes.element` 对应的 `defaultProp` 的正确值是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件,我希望接受另一个组件作为道具,并渲染它.我希望传递的组件是可选的,并且在这种情况下不渲染任何内容.

以下代码完美运行:

const Component = ({ Inner }) =>(<div style={{ borderStyle: "solid" }}><内部/>

);Component.propTypes = {内部:PropTypes.element};Component.defaultProps = {内部:() =>空值};

然而,在第一次加载页面时,prop-types 抱怨:

<块引用>

警告:失败的道具类型:提供给 Componentfunction 类型的无效道具 Inner,需要一个 ReactElement.

我目前的解决方案是将 propType 重新定义为 PropTypes.oneOfType([PropTypes.element, PropTypes.func]),但这似乎完全不正确.

我的 propTypedefaultProp 实际上应该是什么?

希望对您有所帮助.

I have a component that I wish to accept another component as a prop, and render that. I wish for that passed component to be optional, and render nothing in that case.

The following code works perfectly:

const Component = ({ Inner }) => (
  <div style={{ borderStyle: "solid" }}>
    <Inner />
  </div>
);

Component.propTypes = {
  Inner: PropTypes.element
};

Component.defaultProps = {
  Inner: () => null
};

However, on the first load of the page, prop-types complains:

Warning: Failed prop type: Invalid prop Inner of type function supplied to Component, expected a single ReactElement.

My current solution is to redefine the propType as PropTypes.oneOfType([PropTypes.element, PropTypes.func]), but this seems entirely incorrect.

What should my propType or defaultProp actually be?

SSCCE in a sandbox.

This question is similar to If proptype of element what is the default?, but that has accepted an answer that doesn't work, and even if it did, it's not a great deal of help to me, as I'm using react native for real. I've not framed the question in a manner pertaining to react native, as like I said, my example works, it's just prop-types being a big meanie.

解决方案

Using the type of elementType will resolve your problem.

Component.propTypes = {
  Inner: PropTypes.elementType
};

Since your prop is a react component thus we use elementType. If you ever open the source code for the prop-types you will find this there.

Hope so this is helpful to you.

这篇关于与 `PropTypes.element` 对应的 `defaultProp` 的正确值是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆