输入 React props 会返回错误 [英] Typing React props returns errors

查看:60
本文介绍了输入 React props 会返回错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ANT 设计并对我的应用程序做出反应.我有 2 个组件:

I am using ANT design and react for my application. I have 2 components:

//PARENT
const Test = () => {
  const [state, setState] = useState([]);
  function onChange(
    pagination: TablePaginationConfig,
    filters: Record<string, FilterValue | null>,
    sorter: SorterResult<RecordType> | SorterResult<RecordType>[],
    extra
  ) {
    console.log("params", sorter);
    setState([sorter.order, sorter.field]);
  }
  console.log("params", state);

  return <CustomTable onChange={onChange} />;
};

和:

//CHILD
const CustomTable = ({
  onChange?: (pagination: TablePaginationConfig, filters: Record<string, FilterValue | null>, sorter: SorterResult<RecordType> | SorterResult<RecordType>[], extra: TableCurrentDataSource<RecordType>) => void;
}) => {
  return (
    <Table columns={columns} dataSource={data} onChange={onChange} />
  )
}

你怎么看我尝试为 onChange 函数添加类型.一次作为 CHILD 组件中的道具,另一次作为侧 PARENT 组件中的道具,但我尝试为 sorter 参数添加下一个类型时出错:sorter: SorterResult|SorterResult[],.问题是当我尝试更改 RecordType 泛型时,因为我不知道应该在那里添加什么值.现在我得到了: 'SorterResult 类型不存在属性 'order'|SorterResult[]属性字段"在类型SorterResult"上不存在|SorterResult<any>[]'..在我的例子中,如何为这个函数参数 (sorter) 添加类型?
演示:https://codesandbox.io/s/multiple-sorter-antd4150-forked-ie0o5?file=/index.tsx:341-761

How you can see i try to add types for onChange function. One time as a prop in CHILD component and one time in side PARENT component, but i got an error trying to add the next types for sorter parameter: sorter: SorterResult<RecordType> | SorterResult<RecordType>[],. The issue is when i try to change the RecordType generic, because i don't know what value should i add there. Now i got: Property 'order' does not exist on type 'SorterResult<any> | SorterResult<any>[] and Property 'field' does not exist on type 'SorterResult<any> | SorterResult<any>[]'..How to add types for this function parameter (sorter) in my case?
demo: https://codesandbox.io/s/multiple-sorter-antd4150-forked-ie0o5?file=/index.tsx:341-761

推荐答案

在解构对象时不能传递类型.请将 CustomTable 修改为:

You can't pass type while destructuring an Object. Please modify the CustomTable as:

interface RecordType {
 key: string,
 name: string,
 chinese: number,
 math: number,
 english: number,
}

type Props = {
 onChange?: (pagination: TablePaginationConfig, filters: Record<string, FilterValue | null>, sorter: SorterResult<RecordType> | SorterResult<RecordType>[], extra: TableCurrentDataSource<RecordType>) => void,
}

const CustomTable = ({
  onChange,
}: Props) => {
  return (
    <Table columns={columns} dataSource={data} onChange={onChange} />
  )
}

这篇关于输入 React props 会返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆