简体   繁体   中英

React constructor declare props crash intellisense vscode

Any raison why i cant declare my default props like this? Am new in modern front-end and am come from js vanilla, sorry if seem hard to me understand the logic !

class MenueButtons extends Component {
    constructor(props) {
        super(props);
        this.props = {
            /**@type {number} description*/
            count: props?.count || 0,
            /**@type {string} description*/
            test2: props?.test2 || '',
        }
    }

this append if a avoid to pass all props defined ex: <MenueButtons count='0' /> 图片 Warning: MenueButtons(...): When calling super() in `MenueButtons`, make sure to pass up the same props that your component's constructor was passed.

the only way i can see is proceed like this after the class !

MenueButtons.defaultProps = {
    count: 0,
    test2: '',
};

But for me it look weird, and i lost my intellisense in VsCode ? Any way to declare my props in constructor and get intellisense work fine ?

I try declare in constructor because it the only way to get intelligence work like this. Declare with defaultProps , break suggest and declarative check.


with declare in constructor图片图片


with declare only defaultProps 图片


EDIT: Ok after many test, this look more intuitive and logic for me. 100% compatible with intellisense from vsCode IDE.


/**Class description */
class MenueButtons extends Component {
    constructor(props) {
        super(props);
        /**@type {{aaa?: number, bbb?: string }} */
        this.props
    }

    render() {

not yet perfect, if you have other cleaner idea , or more logic, i am open to any suggestion thank you. I can maybe also create a typedef top of the document for share in defaultProps !

    /**
        * @typedef {Object} _defaultProps - ...descriptions
        * @property {number} [_defaultProps.aaa] - ...descriptions
        * @property {string} [_defaultProps.bbb] - ...descriptions
    */
       /**@type {_defaultProps} */
        this.props

thanks for any help

I guess the main problem here is that you try to reassign this.props . Props should be treated as read-only data within your component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM