注释是代码中关于代码行的有用文本,被应用程序的解释器所忽略。这些不会被用户显示。
React是一个具有可重复使用的组件的UI框架。
组件可以用jsx或tsx语言和CSS编写。
JSX是一种特殊的语法,混合使用JavaScript和html。渲染方法是用jsx语法编写的。然而,HTML语法和javascript语法是不可能的。
Javascript注释可以用在构造器或回调方法(componentDidMount等)或任何函数方法中。
如果JSX使用了Javascript注释,它就会显示在浏览器上。
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class First extends Component {
constructor(props) {
super(props);
//constructor comments
}
componentWillMount() {
}
componentDidMount() {
//constructor comments
}
componentWillReceiveProps(nextProps) {
}
shouldComponentUpdate(nextProps, nextState) {
}
componentWillUpdate(nextProps, nextState) {
}
componentDidUpdate(prevProps, prevState) {
}
componentWillUnmount() {
}
render() {
return (
/* This is multi comments text */
// Single line comments
First component
);
}
}
First.propTypes = {
};
export default First;
显示在浏览器上:
所以有一种特殊的语法来给JSX添加注释
语法:
{
// javascript syntx expression
/** this is multi line comments ofsyntax
}
或
{
// this is single line of syntax
}
这就是javascript注释在{} 中的封装方式。
重要的一点jsx注释在react应用中
- JavaScript注释被包裹在小括号内
{}。 - 单行注释可以在新的一行中加入结束括号
}。 - 评论不显示在浏览器页面以及源代码中
- 特殊的语法
{}应用于渲染方法返回的单行元素内的代码。 - 在渲染方法的外部元素中,你可以使用正常的javascript语法风格。
你可以查看下面的注释使用例子
render() {
/* multi line valid comments */
// single line valid comments
return (
/* multi line valid comments */
// single line valid comments
{/* This is multi comments special syntax
line2
*/}
{// Single line special syntax comments
}
First component
);
}
}
jsx中无效的注释
以下是无效的注释声明
render() {
return (
// single line invalid comments
/* multi line invalid comments
{// Single line invalid comments}
First component
);
}
这将使编译器产生一个反应错误--意外的标记,预期的}。
包裹起来
评论也可以用特殊的语法包含在react JSX中。