【问题标题】:how use props.children with ts如何在 ts 中使用 props.children
【发布时间】:2020-01-26 15:50:35
【问题描述】:

我是打字稿的新手,我尝试正确使用 props.children 和打字稿,但出现错误。

interface IFetcher {
  url: string;
}

const Fetcher: React.FC<IFetcher> = props => {
  const [data, setData] = useState<Array<{}>>();
  const [isLoading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string>("");

  useEffect(() => {...})

  return props.children(data, error, isLoading);
};

这是 props.children 的错误:无法调用可能为“空”或“未定义”的对象。

我用这个技巧来解决它:

interface IFetcher {
  url: string;
}

const Fetcher: React.FC<IFetcher> = props => {
  const [data, setData] = useState<Array<{}>>();
  const [isLoading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string>("");

  useEffect(() => {...})

  return props.children && props.children(data, error, isLoading);
};

但我还有另一个错误:

这个表达式是不可调用的。 没有'string | 类型的成分号码 |真实 | {} | ReactElement ReactElement 组件)> |空) | (新(道具:任何)=> 组件)> |反应节点数组 | ReactPortal' 是可调用的。

我需要帮助才能使用好方法。

编辑 我找到了这个解决方案:

interface IFetcher {
  url: string;
  children(data: Array<{}>, error: string, isLoading: boolean): ReactElement;
}

const Fetcher: React.FC<IFetcher> = props => {
  const [data, setData] = useState<Array<{}>>([]);
  const [isLoading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string>("");

  useEffect(() => {...});

  return props.children(data, error, isLoading);
};

当我定义孩子时,我现在没有错误,但这是正确的解决方案吗?

【问题讨论】:

  • 显然function 不包含在默认的children 类型中(不应该吗?)。 React.FC&lt;T&gt; 进行了覆盖合并,因此您可以覆盖 children 属性的默认类型。

标签: reactjs typescript react-hooks


【解决方案1】:

当您尝试将 children 属性调用为函数时,您必须确保 children 存在。为了让您对孩子进行类型检查,您需要在接口中提供它

interface IFetcher {
  url: string;
  children(data: Array<{}>, error: string, isLoading: boolean): ReactElement;
}

const Fetcher: React.FC<IFetcher> = props => {
  const [data, setData] = useState<Array<{}>>([]);
  const [isLoading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string>("");

  useEffect(() => {...});

  return props.children(data, error, isLoading);
};

【讨论】:

  • 确实,这就是我发现的。 “问题”是孩子是用孩子定义的吗?。
猜你喜欢
  • 2018-07-15
  • 2020-04-30
  • 1970-01-01
  • 1970-01-01
  • 2019-12-02
  • 1970-01-01
  • 1970-01-01
  • 2016-09-29
  • 2021-05-31
相关资源
最近更新 更多