美文网首页
React + TypeScript 组件在接收 props 时

React + TypeScript 组件在接收 props 时

作者: direwolf_ | 来源:发表于2019-07-22 21:47 被阅读0次

    报错如下:
    Type '{ navList: any; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Nav> & Readonly<{}> & Readonly<{ children?: ReactNode; }>'. Property 'navList' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Nav> & Readonly<{}> & Readonly<{ children?: ReactNode; }>'.

    错误代码:

    import React from 'react';
    
    class Nav extends React.PureComponent<{
      
    },{
      
    }> {
      constructor(props) {
        super(props);
        this.state = {
          
        };
      }
    
      render () {
        const navList = this.props && this.props.navList || {};
        return (
          <div>
           
          </div>
        )
      }
    }
    
    export default Nav;
    

    问题是我们在这里把 props描述成了一个空对象。

    改正之后:

    import React from 'react';
    
    class Nav extends React.PureComponent<{
      navList?: any
    },{
      
    }> {
      constructor(props) {
        super(props);
        this.state = {
          
        };
      }
    
      render () {
        const navList = this.props && this.props.navList || {};
        return (
          <div>
           
          </div>
        )
      }
    }
    
    export default Nav;
    

    注:state 也同样存在这个问题,详见:https://www.jianshu.com/p/a2f45dc7d45c

    相关文章

      网友评论

          本文标题:React + TypeScript 组件在接收 props 时

          本文链接:https://www.haomeiwen.com/subject/bhuwlctx.html