Analysis of the problem that optional boolean type props in React TypeScript are recognized as non-boolean types
P粉035600555
P粉035600555 2024-03-29 12:02:04
0
1
267

I ran into a weird problem and I'm sure I'm missing something.

This is my Box function/component

export interface BoxProps extends React.HTMLProps<HTMLDivElement> {
    padding?: boolean
    stretch?: boolean
    flex?: boolean
    column?: boolean
    clickable?: boolean
    gap?: boolean
}

function Box (props: BoxProps) {
    return <div className={clsx(
        'flexbox',
        props.column && 'column',
        props.stretch && 'stretch',
        props.padding && 'padding',
        props.flex && 'flex',
        props.clickable && 'clickable',
        props.gap && 'gap',
        props.className
    )} {...props} />
}

Box.defaultProps = {

    padding: false,
    stretch:  false,
    flex:  false,
    column:  false,
    clickable:  false,
    gap:  false,
}

export default Box

All props are Boolean values, the default value is false, and they are all nullable (obviously)

But I still get the following warning on the console:

Warning: Received a false value for non-boolean property clickable.

I get this warning for every props

I don't understand how to create a component like this:

<Box gap stretch>{children}</Box> 等同于 <Box gap={true} ...

without receiving this warning.

I have tried many methods and may not be able to tell you every method.

P粉035600555
P粉035600555

reply all(1)
P粉128563140

This is because the div element does not have these attributes (padding, gap, etc.).

You should remove the {...props} part in your code. The modified code should look like this:

function Box (props: BoxProps) {
    return <div className={clsx(
        'flexbox',
        props.column && 'column',
        props.stretch && 'stretch',
        props.padding && 'padding',
        props.flex && 'flex',
        props.clickable && 'clickable',
        props.gap && 'gap',
        props.className
    )} />
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!