TypeScript 将道具传递给孩子

时间:2021-03-03 15:21:00

标签: reactjs typescript

我是 TypeScript 的新手,我正在尝试将一些 props 发送到 children,通常我会这样做, - 也许这不是最好的方法。

app.js

import React form 'react'
import Component from './component'

const App = () => {

  const myfunc1 = () => 'some function 1'
  const myfunc2 = () => 'some function 2'
  const myfunc3 = () => 'some function 3'
  const var1 = 'some variable 1'
  const var2 = 'some variable 2'

  return (
    <Component 
      myfunc1={myfunc1}
      myfunc2={myfunc2}
      myfunc3={myfunc3}
      var1={var1}
      var2={var2}
    />
  )

}

component.js

import React from 'react'

const Component = ({
  myfunc1,
  myfunc2,
  myfunc3,
  var1,
  var2,
}) => (
   <>
    // Use the props on the component
   </>
)

export default Component

但是在使用 TypeScript 时,它要求对 props 上的所有 Component 进行类型声明。

是否有更好更简单的方法来传递 props 以便我不必在所有 props 上声明类型?

1 个答案:

答案 0 :(得分:2)

import { FunctionComponent } from 'react';


type Props = {
  // types...
}

const Component: FunctionComponent<Props> = ({
  myfunc1,
  myfunc2,
  myfunc3,
  var1,
  var2,
}) => (
<>
</>
)