Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 views
in Technique[技术] by (71.8m points)

reactjs - React.forwardRef/Typescript defaultProps not working

We have a react component library for my own project. It was written in js (Customized material-ui library ;)) ). I have task to migrate components from js to ts, one by one.
Here is an example of component :

import * as React from 'react';
import classNames from 'classnames';

import Typography from '../Typography';

import styles from './link.scss';

type LinkPropTypes = {
    className: string,
    component: React.ElementType,
    children: React.ReactNode,
    color: 'error' | 'inherit' | 'initial' | 'primary' | 'secondary' | 'text-primary' | 'text-secondary',
    underline: 'none' | 'always' | 'hover',

};

const Link = React.forwardRef<HTMLElement, LinkPropTypes>((props, ref) => {
    const {
        color,
        component,
        underline ,
        className: classNameProp,
        ...restProps
    } = props;

    const className = classNames(
        styles[`link--underline-${underline}`],
        classNameProp,
    );

    return (
        <Typography
            className={className}
            color={color}
            component={component}
            ref={ref}
            {...restProps}
        />
    );
});

Link.displayName = 'Link';

Link.defaultProps  = {
    component: 'a',
    color: 'primary',
    underline: 'hover'
} ;
export default Link;

When I try to use this component in main app, it gives such error

<Link>asdasd</Link>

Type '{ children: string; }' is missing the following 
properties from type 'PropTypes': component, color, underline

But when I pass all props it works correctly:

<Link color="primary" underline="hover" component="a">asdasd</Link>

It asks for required parameters such as color, component, and underline. Even if they were in defaultProps.
I tried to assign defaultProps when destructuring props in component :

const {
        color = "primary",
        component = "a",
        underline ="hover",
        className: classNameProp,
        ...restProps
    } = props;

But storybook documentation can't recognize these defaultProps.
I don't want to duplicate defaultValues just for storybook documentation.

So my question is, is there any ways to assign defaultValues by Component.defaultProps in typescript??

question from:https://stackoverflow.com/questions/65839395/react-forwardref-typescript-defaultprops-not-working

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...