React + TypeScript 组件在接收 props 时

2019-07-22  本文已影响0人  direwolf_

报错如下:
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

上一篇 下一篇

猜你喜欢

热点阅读