• React+TypeScript 声明组件的属性和默认值


    What are component properties?

    先创建ch03的React项目。

    npm create vite
    

    In React, component properties, commonly known as props, allow us to pass data from a parent component to its child components. Props provide a way to customize and configure components, making them flexible and reusable. Props are read-only, meaning that the child component should not modify them directly. Instead, the parent component can update the props value and trigger a re-render of the child component with the updated data.When defining a function component, you can access the props passed to it as a parameter:

    在React中,组件属性(通常称为props)允许我们将数据从父组件传递给它的子组件。Props提供了一种自定义和配置组件的方法,使它们变得灵活和可重用。Props是只读的,这意味着子组件不应该直接修改它们。相反,父组件可以更新props值,并用更新后的数据触发子组件的重新呈现。当定义一个函数组件时,你可以访问作为参数传递给它的props:

    新增:src/MyComponent.tsx

    interface MyComponentProperties {
      title: string;
      description: string;
    }
    
    export default function MyComponent(props: MyComponentProperties) {
      return (
        

    {props.title}

    {props.description}

    ); }

    修改:src/App.tsx

    import MyComponent from "./MyComponent";
    
    function App() {
      return (
        <>
          
        
      );
    }
    
    export default App;
    

    修改:src/main.tsx

    import React from "react";
    import ReactDOM from "react-dom/client";
    import App from "./App.tsx";
    
    ReactDOM.createRoot(document.getElementById("root")!).render(
      
        
      
    );
    

    In the above example, the MyComponent function component receives the props object as a parameter. We can access the individual props by using dot notation, such as props.title and props.description , to render the data within the component’s JSX markup. It is also possible to access props using destructuring:

    在上面的例子中,MyComponent函数组件接收props对象作为参数。我们可以使用点表示法(如props)访问单个道具。title和props.description,以在组件的JSX标记中呈现数据。也可以使用解构来访问props:

    新增:src/MyComponent2.tsx

    interface MyComponentProperties {
      title: string;
      description: string;
    }
    
    export default function MyComponent2({
      title,
      description,
    }: MyComponentProperties) {
      return (
        

    {title}

    {description}

    ); }

    As you can see this approach is even cleaner and also allow us to use another destructuring feature, default values which we will discuss in this chapter.

    正如你所看到的,这种方法更加简洁,并且还允许我们使用另一个解构特性,默认值,我们将在本章中讨论。

    Passing property values

    React component properties are set by passing JSX attributes to the component when it is rendered. In Chapter 6, Type Checking and Validation with TypeScript, I’ll go into more detail about how to validate the property values that are passed to components. Now let’s create a couple of components in addition to MyComponent that expect different types of property values:

    React组件属性是通过在呈现组件时将JSX属性传递给组件来设置的。在第6章,TypeScript类型检查和验证中,我将更详细地介绍如何验证传递给组件的属性值。现在,除了MyComponent之外,我们再创建几个组件,它们需要不同类型的属性值:

    新增:MyButton.tsx

    interface MyButtonProperties {
      disabled: boolean;
      text: string;
    }
    
    export default function MyButton({ disabled, text }: MyButtonProperties) {
      return ;
    }
    

    This simple button component expects a Boolean disabled property and a string text property. While we create components to show how we can pass following props, you can notice how we already pass these properties to the button HTML element:

    • disabled property we put into button attribute with the name disabled
    • text property we were pass to the button as a child attribute.

    这个简单的按钮组件需要一个布尔禁用属性和一个字符串文本属性。当我们创建组件来展示如何传递以下props时,你可以注意到我们已经将这些属性传递给了button HTML元素:

    • disabled属性我们把名称为disabled的按钮属性
    • text属性作为子属性传递给按钮。

    Also important to know, any JavaScript expression you want to pass to the component should be wrapped with curly braces.Let’s create one more component that expects an array property value:

    同样重要的是要知道,您想要传递给组件的任何JavaScript表达式都应该用花括号包装。让我们再创建一个需要数组属性值的组件:

    新增:src/MyList.tsx

    interface MyListProperties {
      items: string[];
    }
    
    export default function MyList({ items }: MyListProperties) {
      return (
        
      {items.map((v) => (
    • {v}
    • ))}
    ); }

    You can pass just about anything you want as a property value via JSX, just as long as it’s a valid JavaScript expression. The MyList component accepts an items property, an array that is mapped to li elements.Now, let’s write some code to set these property values:

    你可以通过JSX传递任何你想要的属性值,只要它是一个有效的JavaScript表达式。MyList组件接受items属性,这是一个映射到li元素的数组。现在,让我们编写一些代码来设置这些属性值:

    新增:MyComponent3.tsx

    import MyButton from "./MyButton";
    import MyComponent from "./MyComponent2";
    import MyList from "./MyList";
    
    export default function MyComponent3() {
      const items = ["React", "Golang", "Python"];
      return (
        
    ); }

    修改:src/App.tsx

    import MyComponent from "./MyComponent3";
    
    function App() {
      return (
        <>
          
        
      );
    }
    
    export default App;
    

    Default property values

    In addition to passing data, we can also specify default values for props using the defaultProps property. This is helpful when a prop is not provided, ensuring that the component still behaves correctly:

    除了传递数据,我们还可以使用defaultProps属性指定props的默认值。当没有提供道具时,这很有帮助,确保组件仍然正常运行:

    新增:MyButton2.tsx

    interface MyButtonProperties {
      disabled?: boolean;
      text?: string; // 问号表示可选属性
    }
    
    export default function MyButton2({
      disabled = false,
      text = "按钮",
    }: MyButtonProperties) {
      return ;
    }
    

    新增:MyComponent4.tsx

    import MyButton from "./MyButton2";
    import MyComponent from "./MyComponent2";
    import MyList from "./MyList";
    
    export default function MyComponent4() {
      const items = ["React", "Golang", "Python"];
      return (
        
    ); }

    Using destructuring we can define props and set default value right inside function. Its cleaner and easy to see in cases when we have a big component with a lot of props.In the upcoming sections, we will further dive into component state with hooks, and other key concepts.

    使用解构,我们可以在函数内部定义道具并设置默认值。当我们有一个有很多道具的大组件时,它更清晰,更容易看到。在接下来的部分中,我们将通过钩子和其他关键概念进一步深入组件状态。

  • 相关阅读:
    AN动画基础——摄像头
    knn算法详解
    【Try to Hack】vulnhub DC2
    Linux常用命令、tomcat常用命令
    TS复习---typeScript介绍
    DevOps|研发效能团队组织架构和能力建设
    C++11 右值,右值引用,移动构造,移动赋值
    3.线性神经网络-3GPT版
    唐山海德教育二级建造师报考-----考试科目
    微前端:quankun
  • 原文地址:https://blog.csdn.net/qq_37703224/article/details/139312918