[英]What is the proper way to handle prop-types for a component that uses object destructing and object rest...spread to collect props
I have a component like so:我有一个这样的组件:
import React from 'react'
import { bool } from 'prop-types'
const Component = ({ active, ...rest}) => (
// ...does things
)
Component.propTypes = {
active: bool.isRequired,
// -> how do i handle { ...rest } here?
rest: object // ? works, but is it the right solution?
}
Component
destructures its props
, grabbing the active
prop and collecting the "rest" into rest
. Component
解构其props
,获取active
prop 并将“其余”收集到rest
中。 Is there a way to validate rest
using prop-types
?有没有办法使用
prop-types
验证rest
? Is it required?是必需的吗? Not sure what to do.
不知道该怎么办。
https://www.ian-thomas.net/custom-proptype-validation-with-react/ https://www.ian-thomas.net/custom-proptype-validation-with-react/
Basically, prop-types does allow custom validation. 基本上,prop-types确实允许自定义验证。 You set it to
你把它设置为
Component.propTypes = {
rest: function(props, propName, componentName) { // return null if all is well }
}
Although it's late, here I'm leaving a snippet of how I do things in case I want to extend a library or same concept can be utilized when building own component虽然已经很晚了,但我在这里留下了一段我如何做的事情,以防我想扩展一个库或者在构建自己的组件时可以使用相同的概念
(This is in case you don't want to use typescript and stay with plain old javascript) (这是为了防止您不想使用 typescript 并继续使用普通的旧 javascript)
import React from "react";
import PropTypes from "prop-types";
import { Button } from "reactstrap";
let BtnBaseProps = Object.assign(
{
leftIcon: "",
rightIcon: "",
},
Button.prototype.props
);
/**
*
* @param {BtnBaseProps} props
* @returns
*/
const BtnBase = (props) => {
return (
<Button {...props}>
{props.leftIcon ? <i className={sicon + " mr-2"} /> : null}
{props.children}
{props.rightIcon ? <i className={eicon + " ml-2"} /> : null}
</Button>
);
};
BtnBase.propTypes = {
leftIcon: PropTypes.string,
rightIcon: PropTypes.string,
...(Button.propTypes && Button.propTypes),
};
export default BtnBase;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.