【问题标题】:Type 'string' is not assignable to type '(url: string) => string'.ts(2322)类型 'string' 不可分配给类型 '(url: string) => string'.ts(2322)
【发布时间】:2020-07-05 02:53:54
【问题描述】:

我有这个素材ui版权组件:

export default function Copyright(link: string, text: string) {
  return (
    <Typography variant="body2" color="textSecondary" align="center">
      {'Copyright © '}
      <Link color="inherit" href={link}>
        {text}
      </Link>{' '}
      {new Date().getFullYear()}
      {'.'}
    </Typography>
  );
}

如果我尝试这样使用它,我不会收到任何错误:

{Copyright('https://hello.com', 'HELLO')}

但是,如果我尝试这样使用它:

<Copyright link={'https://hello.com'} text={'hello'}></Copyright>

即使我没有在其他任何地方指定任何“url”,我也会在链接上收到此错误:

Type 'string' is not assignable to type '(url: string) => string'.ts(2322)

如何通过第二种方法使用此组件?一个类似的问题建议使用强制转换,但在我的情况下,可能有多个链接我想在将来调用该组件。

【问题讨论】:

    标签: javascript reactjs typescript material-ui react-component


    【解决方案1】:

    如果你想使用

    <Copyright link={"https://hello.com"} text={"hello"} />
    

    你需要像这样定义道具类型

    props: { link: string; text: string }
    

    用法:

    function Copyright(props: { link: string; text: string }) {
      return (
        <Typography variant="body2" color="textSecondary" align="center">
          {"Copyright © "}
          <Link color="inherit" href={props.link}>
            {props.text}
          </Link>{" "}
          {new Date().getFullYear()}
          {"."}
        </Typography>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-10
      • 2023-02-13
      • 2021-07-22
      • 2021-09-26
      • 1970-01-01
      • 2019-11-15
      • 1970-01-01
      • 2023-02-26
      相关资源
      最近更新 更多