使用TypeScript时获取类型的属性不存在错误

时间:2019-09-30 15:07:28

标签: reactjs typescript react-hooks

我是TypeScript的新手,试图了解如何转换要输入的React Hooks代码。目前,我收到以下错误消息:

Property 'openMenu' does not exist on type '{ children?: ReactNode; }'
Property 'toggle' does not exist on type '{ children?: ReactNode; }'
Property 'slidein' does not exist on type '{ children?: ReactNode; }'

这是我的代码:

const Menu: FunctionComponent = ({ openMenu, toggle, slidein }) => {
  return (
    <>
      <div className={`menu ${toggle}`} onClick={openMenu}>
        <div className="bar1"></div>
        <div className="bar2"></div>
        <div className="bar3"></div>
      </div>
      <div className={`expand ${slidein}`}>
        <ul>
          <li>
            <Link to="/" onClick={openMenu}>
              List
            </Link>
          </li>
          <li>
            <Link to="/add-user" onClick={openMenu}>
              Add User
            </Link>
          </li>
          <li>Add Climb</li>
        </ul>
      </div>
    </>
  );
};

export default Menu;

道具是从父App.js文件中发送的,通常情况下可以,但是TypeScript似乎不喜欢这样。我尝试在每个道具旁边添加一个类型,但这也不能解决问题。

package.json

...
"source-map-loader": "^0.2.4",
"ts-loader": "^6.1.2",
"typescript": "^3.6.3",
...

2 个答案:

答案 0 :(得分:1)

FunctionComponent采用通用类型参数P,它代表Menu组件中使用的道具类型。如果未指定P,则将{}类型用作默认类型。此公共对象类型未指定任何属性类型,因此编译器将不知道openMenutoggleslidein

您将要这样指定Menu

// this is just an example. Replace it with your concrete props type
type MenuProps = {
  openMenu(): void;
  toggle: boolean;
  slidein: string;
};

const Menu: FunctionComponent<MenuProps> = ({ openMenu, toggle, slidein }) => {...}

答案 1 :(得分:1)

您需要在函数签名中显式定义prop类型,例如:

 export const Menu = 

({ openMenu, toggle, slidein }: { 
  openMenu: () => void;
  toggle: boolean;
  slidein: boolean;
}) => {

// rest of your code

}

export default Menu;

更好的是,定义道具的类型并将该类型定义传递给函数:

type PropTypes = {
  openMenu: () => void;
  toggle: boolean;
  slideIn: boolean;    
}

并将其传递给函数:

const Menu: FunctionComponent<PropTypes> = ({ openMenu, toggle, slideIn 
}) => {
   ...
}

祝您编程愉快! ☺️