React JSX语法介绍(JS XML)(一种JS语法扩展,允许在JS代码中编写类似HTML的标记语言)Babel编译

06-01 1585阅读

在线调试网站:https://zh-hans.react.dev/learn

文章目录

  • JSX:现代前端开发的声明式语法
    • 概述
    • JSX的本质与工作原理
      • 什么是JSX
      • JSX转换流程
      • JSX语法特性
        • 表达式嵌入(JSX允许在大括号内嵌入任何有效的JavaScript表达式)
        • 属性传递(JSX中的属性传递遵循特定的规则)
        • 条件渲染(JSX支持多种条件渲染模式)
        • 列表渲染(使用map方法渲染数组数据)
        • JSX与传统HTML的区别
          • 属性命名差异
          • 事件处理差异
          • JSX的优势
            • 声明式编程
            • 组件化开发
            • JSX编译过程
              • Babel转换示例
              • 编译配置
              • 最佳实践
                • 组件结构规范
                • 性能优化技巧
                • 常见问题与解决方案
                  • Key属性的重要性
                  • 事件处理中的this绑定
                  • 总结

                    JSX:现代前端开发的声明式语法

                    概述

                    JSX(JavaScript XML)是Facebook开发的一种JavaScript语法扩展,它允许在JavaScript代码中编写类似HTML的标记语言。作为React生态系统的核心组成部分,JSX为开发者提供了一种更直观、更声明式的方式来描述用户界面。

                    JSX的本质与工作原理

                    什么是JSX

                    JSX本质上是一种语法糖,它将类HTML的语法转换为JavaScript函数调用。当编写JSX代码时,实际上是在创建React元素的描述,这些描述最终会被转换为虚拟DOM。

                    // JSX语法(我们写React时需要编写的代码,这种代码浏览器无法识别,需要通过Babel编译)
                    const element = 

                    Hello, World!

                    ; // 转换后的JavaScript(经过Babel编译) const element = React.createElement( 'h1', // 元素类型 https://blog.csdn.net/Dontla/article/details/{ className: 'greeting' }, // 属性对象 'Hello, World!' // 子元素内容 );

                    JSX转换流程

                    JSX语法特性

                    表达式嵌入(JSX允许在大括号内嵌入任何有效的JavaScript表达式)

                    // 变量嵌入
                    const name = "React开发者";
                    const greeting = 

                    欢迎, https://blog.csdn.net/Dontla/article/details/{name}!

                    ; // 函数调用 function formatName(user) https://blog.csdn.net/Dontla/article/details/{ return user.firstName + ' ' + user.lastName; // 拼接用户姓名 } const user = https://blog.csdn.net/Dontla/article/details/{ firstName: '张', // 用户姓 lastName: '三' // 用户名 }; const element = (

                    Hello, https://blog.csdn.net/Dontla/article/details/{formatName(user)}! https://blog.csdn.net/Dontla/article/details/{/* 调用函数并显示结果 */}

                    ); // 主应用组件 export default function MyApp() https://blog.csdn.net/Dontla/article/details/{ return (

                    欢迎来到我的应用

                    https://blog.csdn.net/Dontla/article/details/{/* 使用 element 变量 */} https://blog.csdn.net/Dontla/article/details/{element}
                    ); }

                    React JSX语法介绍(JS XML)(一种JS语法扩展,允许在JS代码中编写类似HTML的标记语言)Babel编译

                    属性传递(JSX中的属性传递遵循特定的规则)

                    参考文章:React JSX属性传递规则(事件处理函数名必须用驼峰式;内联样式必须是JavaScript对象,键名用驼峰命名;className、htmlFor;自定义属性要以data-开头、动态属性绑定)

                    // 字符串属性
                    const element1 = 
                    内容
                    ; // 表达式属性 const isActive = true; // 定义状态变量 const className = isActive ? 'active' : 'inactive'; // 根据状态确定样式类名 const element2 = ( className} // 动态className onClick=https://blog.csdn.net/Dontla/article/details/{() = console.log('点击')} // 事件处理函数 disabled=https://blog.csdn.net/Dontla/article/details/{!isActive} // 动态禁用状态 > 按钮文字 ); // 主应用组件 export default function MyApp() https://blog.csdn.net/Dontla/article/details/{ return (

                    欢迎来到我的应用

                    https://blog.csdn.net/Dontla/article/details/{/* 使用 element1 变量 */} https://blog.csdn.net/Dontla/article/details/{element1} https://blog.csdn.net/Dontla/article/details/{/* 使用 element2 变量 */} https://blog.csdn.net/Dontla/article/details/{element2}
                    ); }

                    React JSX语法介绍(JS XML)(一种JS语法扩展,允许在JS代码中编写类似HTML的标记语言)Babel编译

                    条件渲染(JSX支持多种条件渲染模式)

                    // 用户问候组件
                    function UserGreeting(https://blog.csdn.net/Dontla/article/details/{ isLoggedIn, user, logout }) https://blog.csdn.net/Dontla/article/details/{
                      // 使用三元运算符进行条件渲染
                      return (
                        
                    https://blog.csdn.net/Dontla/article/details/{isLoggedIn ? ( // 如果已登录

                    欢迎回来, https://blog.csdn.net/Dontla/article/details/{user.name}!

                    // 显示欢迎信息 ) : ( // 如果未登录

                    请先登录

                    // 显示登录提示 )} https://blog.csdn.net/Dontla/article/details/{/* 使用逻辑AND运算符 */} https://blog.csdn.net/Dontla/article/details/{isLoggedIn && ( // 只有登录时才显示 logout}退出 )}
                    ); } // 主应用组件 export default function MyApp() https://blog.csdn.net/Dontla/article/details/{ const isActive = true; // 登录状态 const user = https://blog.csdn.net/Dontla/article/details/{ name: "用户" }; // 用户信息 const logout = () => console.log("退出登录"); // 退出登录函数 return (
                    https://blog.csdn.net/Dontla/article/details/{/* 使用 UserGreeting 组件 */} isActive} // 传递登录状态 user=https://blog.csdn.net/Dontla/article/details/{user} // 传递用户信息 logout=https://blog.csdn.net/Dontla/article/details/{logout} // 传递退出函数 /
                    ); }

                    React JSX语法介绍(JS XML)(一种JS语法扩展,允许在JS代码中编写类似HTML的标记语言)Babel编译

                    列表渲染(使用map方法渲染数组数据)

                    import React from 'react';
                    // TodoList 组件
                    function TodoList(https://blog.csdn.net/Dontla/article/details/{ todos, toggleTodo }) https://blog.csdn.net/Dontla/article/details/{
                      return (
                        
                      https://blog.csdn.net/Dontla/article/details/{todos.map((todo) => ( // 遍历待办事项数组 todo.id} // 为每个元素提供唯一key className=https://blog.csdn.net/Dontla/article/details/{todo.completed ? 'completed' : ''} // 根据完成状态设置样式 https://blog.csdn.net/Dontla/article/details/{todo.text} https://blog.csdn.net/Dontla/article/details/{/* 显示任务内容 */} () = toggleTodo(todo.id)} // 切换完成状态的处理函数 > https://blog.csdn.net/Dontla/article/details/{todo.completed ? '撤销' : '完成'} https://blog.csdn.net/Dontla/article/details/{/* 根据状态显示按钮文字 */}
                  • ))}
                  ); } // 主应用组件 export default function MyApp() https://blog.csdn.net/Dontla/article/details/{ // 使用 useState 管理待办事项状态 const [todos, setTodos] = React.useState([ https://blog.csdn.net/Dontla/article/details/{ id: 1, text: '学习 React', completed: false }, https://blog.csdn.net/Dontla/article/details/{ id: 2, text: '写代码练习', completed: true }, https://blog.csdn.net/Dontla/article/details/{ id: 3, text: '阅读文档', completed: false } ]); // 处理待办项状态切换 const toggleTodo = (id) => https://blog.csdn.net/Dontla/article/details/{ setTodos(todos.map(todo => todo.id === id ? https://blog.csdn.net/Dontla/article/details/{ ...todo, completed: !todo.completed } : todo )); }; return (

                  待办事项

                  https://blog.csdn.net/Dontla/article/details/{/* 使用 TodoList 组件并传递必要 props */} todos} // 传递待办事项数组 toggleTodo=https://blog.csdn.net/Dontla/article/details/{toggleTodo} // 传递状态切换函数 /
                  ); }

                  React JSX语法介绍(JS XML)(一种JS语法扩展,允许在JS代码中编写类似HTML的标记语言)Babel编译

                  JSX与传统HTML的区别

                  属性命名差异

                  HTML属性JSX属性说明
                  classclassName避免与JavaScript关键字冲突
                  forhtmlFor避免与for循环关键字冲突
                  tabindextabIndex采用驼峰命名法

                  事件处理差异

                  // HTML方式
                  // 点击
                  // JSX方式
                  function MyComponent() https://blog.csdn.net/Dontla/article/details/{
                    const handleClick = () => https://blog.csdn.net/Dontla/article/details/{           // 定义事件处理函数
                      console.log('按钮被点击了');        // 输出点击日志
                    };
                    return (
                      handleClick}      https://blog.csdn.net/Dontla/article/details/{/* 使用驼峰命名的事件属性 */}
                        点击
                      
                    );
                  }
                  

                  JSX的优势

                  声明式编程

                  JSX采用声明式编程范式,开发者只需要描述界面应该是什么样子,而不需要关心如何操作DOM:

                  // 声明式:描述最终状态
                  function Counter() https://blog.csdn.net/Dontla/article/details/{
                    const [count, setCount] = useState(0); // 状态管理Hook
                    return (
                      

                  当前计数: https://blog.csdn.net/Dontla/article/details/{count}

                  https://blog.csdn.net/Dontla/article/details/{/* 显示当前计数值 */} () = setCount(count + 1)} // 点击时增加计数 > 增加
                  ); }

                  组件化开发

                  JSX天然支持组件化开发模式:

                  // 可复用的按钮组件
                  function Button(https://blog.csdn.net/Dontla/article/details/{ children, variant = 'primary', onClick }) https://blog.csdn.net/Dontla/article/details/{
                    // 根据variant构建样式类名
                    // `btn` 是基础样式类名(定义按钮基本样式)
                    // `btn-${variant}` 是动态样式类名(根据传入的variant参数变化)
                    // 比如当 variant="primary" 时,最终类名是 "btn btn-primary"
                    const className = `btn btn-$https://blog.csdn.net/Dontla/article/details/{variant}`;  
                    return (
                      className}              // 应用样式类
                        onClick=https://blog.csdn.net/Dontla/article/details/{onClick}                  // 绑定点击事件
                      
                        https://blog.csdn.net/Dontla/article/details/{children}                         https://blog.csdn.net/Dontla/article/details/{/* 渲染子元素 */}
                      
                    );
                  }
                  // 使用组件
                  function App() https://blog.csdn.net/Dontla/article/details/{
                    return (
                      
                  https://blog.csdn.net/Dontla/article/details/{/* 主要按钮示例 */} () = alert('主要按钮')}> 主要按钮 https://blog.csdn.net/Dontla/article/details/{/* 作为children传递 */} https://blog.csdn.net/Dontla/article/details/{/* 次要按钮示例 */} () = alert('次要按钮')}> 次要按钮
                  ); }

                  JSX编译过程

                  Babel转换示例

                  // 原始JSX代码
                  const element = (
                    

                  标题

                  段落内容

                  ); // Babel编译后的代码 const element = React.createElement( "div", // 元素类型 https://blog.csdn.net/Dontla/article/details/{ className: "container" }, // 属性对象 React.createElement("h1", null, "标题"), // 第一个子元素 React.createElement("p", null, "段落内容") // 第二个子元素 );

                  编译配置

                  现代构建工具中的JSX配置:

                  // Babel配置 (.babelrc)
                  https://blog.csdn.net/Dontla/article/details/{
                    "presets": [
                      "@babel/preset-react"               // React预设,包含JSX转换
                    ],
                    "plugins": [
                      "@babel/plugin-transform-react-jsx" // JSX转换插件
                    ]
                  }
                  

                  最佳实践

                  组件结构规范

                  // 推荐的组件结构
                  function UserCard(https://blog.csdn.net/Dontla/article/details/{ user, onEdit, onDelete }) https://blog.csdn.net/Dontla/article/details/{
                    // 1. 状态和副作用Hook
                    const [isEditing, setIsEditing] = useState(false);
                    // 2. 事件处理函数
                    const handleEditClick = () => https://blog.csdn.net/Dontla/article/details/{       // 编辑按钮点击处理
                      setIsEditing(true);                 // 进入编辑模式
                      onEdit(user.id);                    // 调用父组件传入的编辑回调
                    };
                    const handleDeleteClick = () => https://blog.csdn.net/Dontla/article/details/{     // 删除按钮点击处理
                      if (window.confirm('确定要删除吗?')) https://blog.csdn.net/Dontla/article/details/{ // 确认删除操作
                        onDelete(user.id);                // 调用删除回调
                      }
                    };
                    // 3. 渲染逻辑
                    return (
                      
                  user.avatar} alt=https://blog.csdn.net/Dontla/article/details/{user.name} / https://blog.csdn.net/Dontla/article/details/{/* 用户头像 */}

                  https://blog.csdn.net/Dontla/article/details/{user.name}

                  https://blog.csdn.net/Dontla/article/details/{/* 用户姓名 */}

                  https://blog.csdn.net/Dontla/article/details/{user.email}

                  https://blog.csdn.net/Dontla/article/details/{/* 用户邮箱 */}
                  handleEditClick}编辑 handleDeleteClick}删除
                  ); }

                  性能优化技巧

                  // 使用React.memo进行组件优化
                  const MemoizedUserCard = React.memo(UserCard, (prevProps, nextProps) => https://blog.csdn.net/Dontla/article/details/{
                    // 自定义比较函数,只有user对象变化时才重新渲染
                    return prevProps.user.id === nextProps.user.id &&
                           prevProps.user.name === nextProps.user.name;
                  });
                  // 使用useCallback优化事件处理函数
                  function UserList(https://blog.csdn.net/Dontla/article/details/{ users, onUserUpdate }) https://blog.csdn.net/Dontla/article/details/{
                    const handleUserEdit = useCallback((userId) => https://blog.csdn.net/Dontla/article/details/{
                      // 编辑逻辑,使用useCallback避免子组件不必要的重渲染
                      onUserUpdate(userId);
                    }, [onUserUpdate]);                   // 依赖数组
                    return (
                      
                  https://blog.csdn.net/Dontla/article/details/{users.map(user => ( user.id} // 稳定的key值 user=https://blog.csdn.net/Dontla/article/details/{user} onEdit=https://blog.csdn.net/Dontla/article/details/{handleUserEdit} // 优化后的回调函数 / ))}
                  ); }

                  常见问题与解决方案

                  Key属性的重要性

                  // 错误示例:缺少key或使用不稳定的key
                  function BadList(https://blog.csdn.net/Dontla/article/details/{ items }) https://blog.csdn.net/Dontla/article/details/{
                    return (
                      
                    https://blog.csdn.net/Dontla/article/details/{items.map((item, index) => ( index} https://blog.csdn.net/Dontla/article/details/{/* 使用index作为key是不推荐的 */} https://blog.csdn.net/Dontla/article/details/{item.name}
                • ))}
                ); } // 正确示例:使用稳定唯一的key function GoodList(https://blog.csdn.net/Dontla/article/details/{ items }) https://blog.csdn.net/Dontla/article/details/{ return (
                  https://blog.csdn.net/Dontla/article/details/{items.map((item) => ( item.id} https://blog.csdn.net/Dontla/article/details/{/* 使用唯一ID作为key */} https://blog.csdn.net/Dontla/article/details/{item.name}
              • ))}
              ); }

              事件处理中的this绑定

              // 类组件中的事件绑定
              class MyComponent extends React.Component https://blog.csdn.net/Dontla/article/details/{
                constructor(props) https://blog.csdn.net/Dontla/article/details/{
                  super(props);
                  this.state = https://blog.csdn.net/Dontla/article/details/{ count: 0 };
                  
                  // 方法1:在构造函数中绑定
                  this.handleClick = this.handleClick.bind(this);
                }
                // 方法2:使用箭头函数
                handleClick = () => https://blog.csdn.net/Dontla/article/details/{
                  this.setState(https://blog.csdn.net/Dontla/article/details/{ count: this.state.count + 1 });
                };
                render() https://blog.csdn.net/Dontla/article/details/{
                  return (
                    this.handleClick}  https://blog.csdn.net/Dontla/article/details/{/* 正确绑定的事件处理器 */}
                      计数: https://blog.csdn.net/Dontla/article/details/{this.state.count}
                    
                  );
                }
              }
              

              总结

              JSX作为React生态系统的核心语法扩展,通过其声明式的特性和强大的表达能力,大大简化了前端开发的复杂度。它不仅提供了直观的组件编写方式,还通过编译时优化确保了运行时的高效性能。

              理解JSX的工作原理和最佳实践,对于掌握现代React开发至关重要。随着前端生态的不断发展,JSX的应用场景也在不断扩展,从传统的Web应用到React Native移动开发,JSX都展现出了其强大的适应性和实用性。

              通过合理运用JSX的各种特性,开发者能够构建出更加优雅、可维护的用户界面,这正是JSX在现代前端开发中不可替代的价值所在。

免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们。

目录[+]

取消
微信二维码
微信二维码
支付宝二维码