美文网首页
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 时

    报错如下:Type '{ navList: any; }' is not assignable to type '...

  • React进阶组件--props、组件通讯(React学习笔记_

    React进阶组件 组件的props、组件通信 组件的props 组件是封闭的,要接收外部数据应该通过props来...

  • Props&State

    Props 当 React 元素为用户自定义组件时,它会将 JSX 所接收的属性(attributes)以及子组件...

  • vue、react对比

    一、父子通信 1. 父组件通过props向子组件传值 vue:父组件 子组件接收 react:父组件: 子组件: ...

  • 常见面试题总结(二)

    immutable如何优化react项目性能 react组件接收新的state和props之后默认会发生渲染,即使...

  • React - 组件

    组件:接收任意入参,并返回 React 元素。 1. 函数组件 函数组件:接收唯一带有数据的 props 对象,并...

  • 04:class组件与生命周期

    class组件基础 React的组件可以定义为 class 或者 函数 的形式。组件接收Props输入,并返回Re...

  • 05react基础-组件通讯

    组件的props 组件时封闭的,要接受外部数据应该通过props来实现 props的作用:接收传递给组件的数据 传...

  • React知识点记录

    函数组件 React.FC 函数组件是最简单的组件定义方式,它接收唯一的 props 参数 useState 通过...

  • React组件设计模式-Provider-Consumer

    React组件设计模式-组合组件 React组件设计模式-Render-props 我们都知道,基于props做组...

网友评论

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

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