我的 React 之旅:第 23 天
Props 和 State
**道具**
Props 是 的缩写,是从父组件传递给子组件的“只读”且“不可变”的数据。它们主要用于在组件之间传递数据并确保可重用性。
**Props 的主要特点**
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,
};**状态**
状态是组件内的一个对象,它保存着随时间变化的动态值。状态是可变的,通常用于用户交互和事件。
**州的主要特征**
**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(
);**总结**