首页 > 解决方案 > TypeScript 属性需要什么数据类型传递给 React 组件中的函数

问题描述

我正在创建一个基本的 TypeScript React 项目来熟悉 React 和 TypeScript,因为我以前从未使用过这两种技术。

下面是一个基本组件,作为我正在学习的课程的一部分,我将它放在一起,但是该课程没有使用 TypeScript,所以我必须在进行时进行调整。

据我了解 TypeScript,您必须明确说明您在组件中使用的每个属性的数据类型。现在我试图引入一个“点击”属性,我将向它传递一个函数,但我不知道哪种数据类型是必要的。

import React, { MouseEventHandler } from 'react';

type PersonProps = {
    name: string,
    age: number,
    children: string,
    click?: 
  }
  
const Person = ({name, age, children, click}: PersonProps) => (
    <div>
        <p onClick={click}>I'm {name} and I'm {age} years old.</p>
        <p>{children}</p>
    </div>
);

export default Person;

下面是我将函数传递到属性字段的代码

const App = () => {
  const [personsState, setPersonsState] = useState({
        persons: [
          { name: 'Max', age: 16},
          { name: "Theo", age: 27},
          { name: "Tom", age: 63}
        ],
        otherState: 'some other value'
      });

  const [otherState, setotherState] = useState('Some other value');

  console.log(personsState, otherState);

  const switchNameHandler = () => {
      setPersonsState({
        persons: [
          { name: 'Jeff', age: 16},
          { name: "Bob", age: 27},
          { name: "Kyle", age: 90}
        ],
        otherState: personsState.otherState
      });
  };

  return (
    <div className="App">
      <h1>Hi, I'm a React App</h1>
      <p>This is really working!</p>
      <button onClick={switchNameHandler}>Switch Name</button>
      <Person 
        name={personsState.persons[0].name} 
        age={personsState.persons[0].age}>My Hobbies: Racing</Person>
      <Person 
        name={personsState.persons[1].name} 
        age={personsState.persons[1].age} 
        click={switchNameHandler}>My Hobbies: Sleep</Person>
      <Person 
        name={personsState.persons[2].name} 
        age={personsState.persons[2].age}>My Hobbies: Design</Person>
    </div>
  );
}

我尝试使用MouseEvent作为数据类型,但没有成功。

标签: javascriptreactjstypescript

解决方案


你可以加

type PersonProps = {
  name: string,
  age: number,
  children: string,
  click?: () => void, 
}

尽管如果将此单击属性绑定到 onClick,则该函数的默认参数将是SyntheticEvent类型

click?: (SyntheticEvent e) => void

推荐阅读