admin管理员组文章数量:1389878
I have a ponent 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
. Is there a way to validate rest
using prop-types
? Is it required? Not sure what to do.
I have a ponent 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
. Is there a way to validate rest
using prop-types
? Is it required? Not sure what to do.
- 1 There won't be a way to handle that through a loop without knowing all props ahead of time. You'll have to manually enter each value that you know could be a possible prop. – Chase DeAnda Commented Mar 9, 2018 at 16:25
2 Answers
Reset to default 6https://www.ian-thomas/custom-proptype-validation-with-react/
Basically, prop-types does allow custom validation. You set it to
Component.propTypes = {
rest: function(props, propName, ponentName) { // 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 ponent
(This is in case you don't want to use typescript and stay with plain old 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;
本文标签:
版权声明:本文标题:javascript - What is the proper way to handle prop-types for a component that uses object destructing and object rest...spread t 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744595340a2614741.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论