使用TypeScript进行反应:类型“ {}”不可分配给类型

时间:2018-07-03 13:27:53

标签: reactjs typescript

我在React中有一个组件,该组件显示基于道具的导航。我无法弄清楚为什么在尝试运行应用程序时出现此错误:

(19,8): Type '{}' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<TableSystems> & Readonly<{ children?: ReactNode; }...'.
  Type '{}' is not assignable to type 'Readonly<{ todos: any; showNav: boolean; }>'.
    Property 'todos' is missing in type '{}'.

我的组件看起来像这样:

import * as React from 'react'
import Navigation from '../components/Navigation'
import TableSystems from '../components/TableSystems'

class SystemTable extends React.PureComponent<{showNav: boolean }> {
  render(){
  return (

    <div >
    <div >
    <div className="navigationContainer">
    <Navigation {...this.props.showNav} className="sideMenu"/>
      <TableSystems/>
      </div>
    </div>
  </div>)
  }
}


export default SystemTable

我在这里找不到问题所在。

该组件如下所示:

import * as React from 'react';
import history from '../history';


class Navigation extends React.Component<any>  {

constructor(props){
    super(props);
    this.toVersions = this.toVersions.bind(this);
  }

  toVersions(){
    history.push('/versions');
  }

  render() {
    var style = this.props.visible ? "toggled" : "";
    console.log(style);
    return (
      <div className={style} id="wrapper">


        <div id="sidebar-wrapper">
          <ul className="sidebar-nav">
            <li className="sidebar-brand">
              <a href="#">
                Menu
              </a>
            </li>
            <li >
              <a className="nav-link" href="#">List1</a>
            </li>
            <li >
              <a className="nav-link" href="#">List2</a>
            </li>
            <li >
              <a className="nav-link" href="" onClick={this.toVersions}>List3</a>
            </li>
            <li >
              <a className="nav-link" href="#">List4</a>
            </li>
          </ul>
        </div>
      </div>
    )
  }
}

export default Navigation

3 个答案:

答案 0 :(得分:2)

您需要通过将属性todos定义为todos?: any来使属性{ todos: null, showNav: boolean }为可选,否则您必须将一个值传递给它:composer archive create -t dir -n . && \ composer network install -a $BNA_FILE -c PeerAdmin@hlfv1 && \ composer network upgrade -c PeerAdmin@hlfv1 -n NETWORK-NAME -V 0.1.23

答案 1 :(得分:2)

虽然我只能猜测引发错误的元素(不知道第19行在哪里),但错误完全可以说明:

Type '{}' is not assignable to type 'Readonly<{ todos: any; showNav: boolean; }>'. Property 'todos' is missing in type '{}'.

该组件需要一个todo属性和一个showNav属性,您未提供任何这些属性。尝试明确指定道具:

<YourElement todos={ this.props.whatever } showNav={true}> ... </YourElement>

另一种解决方案是使用散布运算符为元素的道具使用对象属性:

const someVar = { todos: "your type for todos here", showNav: true };

<YourElement { ...someVar } \>

确保您还键入了元素的道具:

interface Props {
    prop: string;
}

const SampleElement: React.SFC<Props> = (props) =>
    <div>{props.prop}</div>

class AnotherElement extends React.Component<Props> { ... }

答案 2 :(得分:0)

因此解决方案是将{... this.props}添加到组件中,如下所示:

<TableSystems {...this.props}/>