使用打字稿将自定义道具传递给React组件

时间:2020-08-27 10:59:26

标签: reactjs typescript

我对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>  
);

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

1 个答案:

答案 0 :(得分:0)

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

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

您只需要让Typescript知道组件的道具是什么。