使用 TypeScript 的函数组件中的道具问题

Issues with props in a function component with TypeScript


编辑:

现在我得到这个错误:

Property 'addColumns' does not exist on type 'PropsWithChildren<{ myProps: any; }>'.ts(2339)

使用此代码:

Const Djitsheet: React.FC<{ myProps }> = (props) => {  
 console.log('', props) 
  let dataToPass: Array<any> 
   let addColumnsToPass: boolean = props.addColumns  
 let addRowsToPass: boolean = props.addRows

原文:

我正在尝试将 JSX React 函数组件转换为 TSX 组件。这是实习,这是我第一次尝试。我只需要开始,然后我就会知道从那里去哪里...

我在使用 TS React FC 时在 VS Code 中遇到此错误...

Type '{ (props: myProps): JSX.Element; defaultProps: Partial<{ props: myProps; }>; propTypes: React.WeakValidationMap<{ props: myProps; }>; }' is not assignable to type 'FC<{ props: myProps; }>'.
  Types of parameters 'props' and 'props' are incompatible.
    Type 'PropsWithChildren<{ props: myProps; }>' has no properties in common with type 'myProps'.ts(2322)

这是我的代码。

interface myProps {
  id?: string
  size?: Array<number>
  data?: Array<any>
  headers?: Array<any>
  addColumns?: boolean
  addRows?: boolean
  readonly?: boolean
  snapToData?: boolean
}

const Djitsheet: React.FC<{ props: myProps }> = (props: myProps) => {

return <h1>Hello, from TSX</h1>
}

Djitsheet.defaultProps = {
  id: `my-sheet`,
  size: [4, 4],
  data: undefined,
  headers: [],
  addColumns: true,
  addRows: true,
  readonly: false,
  snapToData: false
}

Djitsheet.propTypes = {
  id: PropTypes.string,
  size: PropTypes.array,
  data: PropTypes.array,
  headers: PropTypes.array,
  addColumns: PropTypes.bool,
  addRows: PropTypes.bool,
  readonly: PropTypes.bool,
  snapToData: PropTypes.bool
}

我在 VS 代码中的 id prop 也收到错误消息:

Type '{ id: string; size: number[]; data: undefined; headers: undefined[]; addColumns: boolean; addRows: boolean; readonly: boolean; snapToData: boolean; }' is not assignable to type 'Partial<{ props: myProps; }>'.
  Object literal may only specify known properties, and 'id' does not exist in type 'Partial<{ props: myProps; }>'.ts(2322)

当您将 interface 传递给声明的 Functional Component 时,避免将其作为嵌套对象传递。

让我们仔细看看您的“编辑”版本:

// Const Djitsheet: React.FC<{ myProps }> = (props) => {

// pass "interface" the same way you pass "type"
Const Djitsheet: React.FC<myProps> = (props) => {
  console.log('', props) 
  let dataToPass: Array<any>;
  let addColumnsToPass: boolean = props.addColumns;
  let addRowsToPass: boolean = props.addRows;
  // ...
}