【问题标题】:React with typescript passing function as props using hooks使用钩子将 typescript 传递函数作为道具进行反应
【发布时间】:2020-05-03 15:16:44
【问题描述】:

我对打字稿很陌生。尝试用 react、typescript 和 hooks 构建一个简单的 crud 应用程序。我不知道如何将数据和函数一起作为道具传递给子组件,该子组件将进一步向他的孩子发送道具。这是一个示例代码。

父组件

const App = () => {
  const [data, setData] = useState([
    { id: 1, name: 'John', email: 'john@gmail.com' },
    { id: 1, name: 'Mike', email: 'mike@gmail.com' },
  ])

 // how to send this function to StudentList component
  const removeStudent = (id: number): void => {
    setData(data.filter(item => item.id !== id))
  }

  return (
    <div>
      <StudentList data={data} removeStudent={removeStudent} />
    </div>
  );
}

子组件/StudentList

interface StudentsInterface {
    id: number,
    name: string,
    email: string,
}

interface PropsFunction {
    removeStudent: () => void
}

const StudentList = ({ data }: { data: StudentsInterface[] }, { removeStudent }: PropsFunction) => {
    console.log('removeStudent ==>', removeStudent) // getting undefined
    return (
        <table id='students'>
            <tbody>
                {data.map((student, index) => {
                    return (
                        <Student student={student} key={index} removeStudent={removeStudent} />
                    )
                })}
            </tbody>
        </table>
    )
}

如果我只是传递数据(StudentList 的第一个参数),我会得到道具,但我也想要 removeStudent 函数...

如果只是反应,我知道我会在 studentList 中解构 {removeStudent} 并完成,但是在打字稿中我必须定义数据类型...

希望我清楚。 由于我对打字稿很陌生,如果您能解释一下我做错了什么,我会很高兴。

【问题讨论】:

  • 我不知道 typescript,但在 javascript 中你会做 const StudentList = ({ data, removeStudent } =&gt; ,我怀疑 typescript 版本期望类似的东西
  • 或许const StudentList = ({ data: StudentsInterface[], removeStudent: PropsFunction } =&gt;

标签: javascript reactjs typescript react-hooks


【解决方案1】:

您使用 2 个参数作为道具:


const StudentList = ({ data, removeStudent }: { data: StudentsInterface[], removeStudent: PropsFunction }) => ...

编辑:

修复它的一种方法是您将PropsFunction 定义为接口,这意味着它是一个具有removeStudent 属性的对象 - 您可能只是希望它是:

type PropsFunction = () => void;

【讨论】:

  • 好的,我已经将我的函数用作道具,但我仍然收到错误“类型'(id:数字)=> void'中缺少属性'removeStudent',但类型'PropsFunction”中需要'跨度>
  • 现在这个新错误“类型 '(id: number) => void' 不可分配给类型 'PropsFunction'。”
  • @user9258981 - 当然不是,但那是打字稿。 - 一种类型接受参数(id: number) 而我发布的PropsFunction 没有,所以修复它。
  • 我在 propsFunction 中传递了一个参数,所以现在它已修复...谢谢
猜你喜欢
  • 2020-06-27
  • 2023-01-19
  • 1970-01-01
  • 1970-01-01
  • 2022-09-11
  • 2020-06-03
  • 2018-01-13
  • 1970-01-01
  • 2017-01-31
相关资源
最近更新 更多