首页 > 解决方案 > TypeScript 将道具传递给孩子

问题描述

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

应用程序.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}
    />
  )

}

组件.js

import React from 'react'

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

export default Component

但是在使用 TypeScript 时,它会要求在 all propson 上进行类型声明Component

有没有更好更简单的传递方式,props所以我不必在 all 上声明类型props

标签: reactjstypescript

解决方案


import { FunctionComponent } from 'react';


type Props = {
  // types...
}

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

推荐阅读