首页 > 解决方案 > 使用打字稿将自定义道具传递给反应组件

问题描述

我对 TypeScript 很陌生,我想知道是否有人可以给我一个将这个 React 组件转换为 TypeScript 的示例:

const Message = ({from, text}) => (
  <div>
    <p>{text}</p>
    <p>from: {from}</p>
  </div>  
);

我尝试过这样的事情:

const Message: React.FC = ({from, text}) => (
  <div>
    <p>{text}</p>
    <p>from: {from}</p>
  </div>  
);

但它给了我错误:类型'{孩子?:ReactNode;上不存在属性'propertyName' }'。

标签: reactjstypescript

解决方案


interface Props {
  from: string;
  to: string;
}

const Message: React.FC<Props> = ({from, text}) => (
  <div>
    <p>{text}</p>
    <p>from: {from}</p>
  </div>  
);

你只需要让 Typescript 知道组件的 props 是什么。


推荐阅读