我的 React 之旅:第 23 天

Props 和 State

**道具**

Props 是 的缩写,是从父组件传递给子组件的“只读”且“不可变”的数据。它们主要用于在组件之间传递数据并确保可重用性。

**Props 的主要特点**

  • 只读:不能被子组件修改。
  • 用于功能和类组件。
  • PropTypes:确保在开发过程中道具具有正确的数据类型。
  • age: PropTypes.number; // Throws a warning if a non-number is passed.

    4.DefaultProps:当没有传递props时,提供默认值。

    name: "Guest"; // Default value for the name prop.

    **代码示例**

    **学生.jsx**

    import PropTypes from 'prop-types';
    
    export default function Student(props) {
      return (
        

    Name: {props.name}

    Age: {props.age}

    Student: {props.isStudent ? 'Yes' : 'No'}

    ); } // PropTypes Student.propTypes = { name: PropTypes.string, age: PropTypes.number, isStudent: PropTypes.bool, }; // DefaultProps Student.defaultProps = { name: 'Guest', age: 0, isStudent: false, };

    **状态**

    状态是组件内的一个对象,它保存着随时间变化的动态值。状态是可变的,通常用于用户交互和事件。

    **州的主要特征**

  • 只能在类组件中使用(在旧版 React 中)。
  • 可变:使用 this.setState() 进行更新。
  • 跟踪动态数据,例如用户输入或实时响应。
  • **App.jsx 实现**

    Props 从 App 组件传递到 Student 组件。

    **App.jsx**

    import React from 'react';
    import Student from './Student';
    
    export default function App() {
      return (
        <>
          
          
          
          
           {/* Uses defaultProps */}
           {/* Partial DefaultProps */}
        
      );
    }

    **在 DOM 中渲染**

    **index.js**

    import React from 'react';
    import { createRoot } from 'react-dom/client';
    import App from './App.jsx';
    
    createRoot(document.getElementById('root')).render(
      
        
      
    );

    **总结**

  • Props:不可变,从父级传递给子级,并用于可重用性。
  • 状态:可变,管理动态行为并通过 this.setState() 进行更新。
  • 在现代 React 中,像 useState 这样的钩子使得函数组件同样能够管理状态,从而无需类组件。