React 中 props 的最常用用法精选+useContext

✅ React 最常用 props 用法 10 例


✅ 1. 传递字符串 / 数字 / 布尔值

复制代码
function UserCard({ name, age, isVip }) {
  return (
    <div>
      {name} - {age} - {isVip ? 'VIP' : '普通用户'}
    </div>
  );
}

<UserCard name="张三" age={18} isVip={true} />

✅ 2. 传递函数(事件)

复制代码
function Button({ onClick }) {
  return <button onClick={onClick}>点我</button>;
}

<Button onClick={() => alert('你好!')} />

✅ 3. 传递 children(嵌套内容)

复制代码
function Layout({ children }) {
  return <div className="layout">{children}</div>;
}

<Layout>
  <p>这是页面内容</p>
</Layout>

✅ 4. 解构 props

复制代码
function Welcome({ name }) {
  return <h1>欢迎 {name}</h1>;
}

✅ 5. 设置默认值

复制代码
function Title({ text = "默认标题" }) {
  return <h2>{text}</h2>;
}

<Title /> // 显示"默认标题"

✅ 6. 传递数组 / 对象

复制代码
function List({ items }) {
  return <ul>{items.map(item => <li key={item}>{item}</li>)}</ul>;
}

<List items={['苹果', '香蕉']} />

✅ 7. props 展开传递(...props)

复制代码
function Input(props) {
  return <input {...props} />;
}

<Input type="text" placeholder="请输入..." />

✅ 8. props 类型校验(开发时用)

复制代码
import PropTypes from 'prop-types';

function User({ name }) {
  return <div>{name}</div>;
}

User.propTypes = {
  name: PropTypes.string.isRequired,
};

✅ 9. 使用函数+参数(如事件传参)

复制代码
function Item({ id, onDelete }) {
  return <button onClick={() => onDelete(id)}>删除</button>;
}

<Item id={1} onDelete={(id) => console.log('删除', id)} />

✅ 10. 父传子 + 子组件回调

复制代码
function Child({ onLogin }) {
  return <button onClick={onLogin}>登录</button>;
}

function Parent() {
  const handleLogin = () => console.log("登录成功!");
  return <Child onLogin={handleLogin} />;
}

✅ 补充:ref 转发(略高阶)

复制代码
const Input = React.forwardRef((props, ref) => (
  <input ref={ref} {...props} />
));

function App() {
  const ref = React.useRef();
  return (
    <>
      <Input ref={ref} />
      <button onClick={() => ref.current.focus()}>聚焦</button>
    </>
  );
}

✅ 小结:最常见的 props 类型

类型 用途 示例
string 展示文字内容 title="标题"
number 计数、评分等 count={5}
boolean 控制显示/开关 isOpen={true}
function 绑定事件 onClick={() => {}}
children 嵌套组件内容 <Comp>内容</Comp>
array 列表/选项 items={[1, 2, 3]}
object 配置项、用户信息等 user={``{ name: '张三' }}
...props 展开传递给 HTML 元素 <button {...props}>按钮</button>

useContext ------ 它是 React 中用于跨组件传递数据的一个非常重要的方式,属于"替代 props 多层传递"的方案。

useContext 和 props 的关系、区别、使用场景与完整例子,并结合 props 的理解一并讲清楚。


✅ React 中 useContext 与 props 的配合与区别


🔍 一句话理解

  • props:父 → 子逐层传递,显式、灵活但繁琐。

  • context + useContext:全局/跨层传递,适合状态共享,如主题、语言、用户登录信息等。


✅ 1. useContext 基本使用步骤

🔧 第一步:创建 Context

复制代码
import { createContext } from "react";

const UserContext = createContext(null);

🔧 第二步:提供 Provider,在顶层注入值

复制代码
function App() {
  return (
    <UserContext.Provider value={{ name: "张三", isVip: true }}>
      <Page />
    </UserContext.Provider>
  );
}

🔧 第三步:在任意子组件中使用 useContext 获取值

复制代码
import { useContext } from "react";

function Page() {
  const user = useContext(UserContext);
  return <div>你好,{user.name},VIP:{user.isVip ? "是" : "否"}</div>;
}

✅ 2. useContext vs props:区别对比

项目 props useContext
数据传递方式 父组件手动一层一层传递 提供一次,全局可用
灵活性 更灵活,每个组件单独定义 更全局,统一管理
代码复杂度 嵌套层级多时变复杂 跨层更简单,避免"prop drilling"
场景 大多数局部传值场景 全局状态,如登录用户、主题、权限、多语言等
性能影响 精细控制每一层渲染 变更会导致所有消费组件重新渲染(需 memo 优化)

✅ 3. useContext + props 混用

复制代码
const ThemeContext = createContext("light");

function Button({ label }) {
  const theme = useContext(ThemeContext);
  return <button className={`btn-${theme}`}>{label}</button>;
}

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Button label="点击我" />
    </ThemeContext.Provider>
  );
}
  • label 是 props 传递的内容

  • theme 是 context 提供的"全局数据"

二者结合用是常见写法。


✅ 4. useContext + props 高级配合场景举例

示例:显示用户名称并支持外部传递自定义 greeting

复制代码
const UserContext = createContext({ name: "匿名用户" });

function Welcome({ greeting = "你好" }) {
  const user = useContext(UserContext);
  return <h1>{greeting},{user.name}</h1>;
}

function App() {
  return (
    <UserContext.Provider value={{ name: "小红" }}>
      <Welcome greeting="欢迎回来" />
    </UserContext.Provider>
  );
}

✅ 5. 注意事项

  • 不推荐把所有数据都放在 context 中,会导致过度渲染。

  • 用 context 的时候,推荐拆小组件 + memo 优化

  • 可以结合 useReducer + useContext 实现简易状态管理(类 Redux)。


✅ 总结一下

方式 说明
props 用于组件直接传递数据,一层层传
useContext 用于全局或跨层组件数据共享(主题/用户/语言)
混合使用 最常见写法:context 提供环境,props 控制行为
相关推荐
崔庆才丨静觅8 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60619 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了9 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅9 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅9 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅10 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment10 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅10 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊10 小时前
jwt介绍
前端
爱敲代码的小鱼10 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax