梗概

  • 类似JSP,在JavaScript中内嵌HTML代码
  • 只能有一个根标签 ^e49jp3
    • 如果有多个标签,have to wrap them into a shared parent, 示例:
      function AboutPage() {
        return (
          <>
            <h1>About</h1>
            <p>Hello there.<br />How do you do?</p>
          </>
        );
      }

使用JSX

  • 浏览器和nodejs不能直接运行jsx,需要一个编译环境,可以是babel或者Vite等打包工具

动态解析js变量

解析字符串

示例

return (
  <h1>
    {user.name}
  </h1>
);
return (
  <img
    className="avatar"
    src={user.imageUrl}
  />
);

解析对象

<img
  className="avatar"
  src={user.imageUrl}
  alt={'Photo of ' + user.name}
  style={{
    width: user.imageSize,
    height: user.imageSize
  }}
/>

style={{}} is not a special syntax, but a regular {} object inside the style={ }

解析数组

const products = [
  { title: 'Cabbage', id: 1 },
  { title: 'Garlic', id: 2 },
  { title: 'Apple', id: 3 },
];

Inside your component, use the map() function to transform an array of products into an array of <li> items:

const listItems = products.map(product =>
  <li key={product.id}>
    {product.title}
  </li>
);
return (
  <ul>{listItems}</ul>
);