簡體   English   中英

React 構造函數聲明 props 崩潰智能感知 vscode

[英]React constructor declare props crash intellisense vscode

為什么我不能像這樣聲明我的默認道具有什么理由嗎? 我是現代前端的新手,來自 js vanilla,如果我覺得很難理解邏輯,對不起!

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

這個 append 如果避免傳遞所有定義的道具,例如: <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.

我能看到的唯一方法是在 class 之后像這樣繼續!

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

但對我來說它看起來很奇怪,我在 VsCode 中失去了智能 有什么方法可以在構造函數中聲明我的道具並讓智能感知工作正常嗎?

我嘗試在構造函數中聲明,因為它是獲得智能工作的唯一方法。 使用defaultProps聲明,中斷建議和聲明性檢查。


在構造函數中聲明圖片圖片


僅聲明 defaultProps 圖片


編輯:好的,經過多次測試,這對我來說看起來更直觀和邏輯。 100% 兼容來自 vsCode IDE 的智能感知。


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

    render() {

還不完美,如果您有其他更清晰的想法或更多邏輯,我願意接受任何建議,謝謝。 我也許還可以在defaultProps中創建文檔的typedef頂部以共享!

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

謝謝你的幫助

我想這里的主要問題是您嘗試重新分配this.props 道具應被視為組件中的只讀數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM