Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSX #16

Open
oliver1204 opened this issue Feb 15, 2019 · 0 comments
Open

JSX #16

oliver1204 opened this issue Feb 15, 2019 · 0 comments

Comments

@oliver1204
Copy link
Owner

浏览器是如何识别 JSX 的?

jsx简介

前端文件大类别上分为: html、css、js,那么,为什么我可以在.jsx文件中写html呢?

这个主要功劳归功于babel.

<div class='box' id='content'>
  <div class='title'>Hello</div>
  <button>Click</button>
</div>

为什么甚至在我们的代码并没有使用 React 的情况下,也需要在文件顶部 import React from 'react'?

由于 JSX 编译后会调用 React.createElement 方法,所以在你的 JSX 代码中必须首先声明 React 变量。

比如,下面两个导入都是必须的,尽管 React 和 CustomButton 都没有在代码中被直接调用。

import React from 'react';
import CustomButton from './CustomButton';

function WarningButton() {
  // 返回 React.createElement(CustomButton, {color: 'red'}, null);
  return <CustomButton color="red" />;
}

每个 DOM 元素的结构都可以用 JavaScript 的对象来表示。你会发现一个 DOM 元素包含的信息其实只有三个:标签名,属性,子元素。

所以其实上面这个 HTML 所有的信息我们都可以用合法的 JavaScript 对象来表示:

{
  tag: 'div',
  attrs: { className: 'box', id: 'content'},
  children: [
    {
      tag: 'div',
      arrts: { className: 'title' },
      children: ['Hello']
    },
    {
      tag: 'button',
      attrs: null,
      children: ['Click']
    }
  ]
}

为什么 JSX 中的组件名要以大写字母开头?

在JSX中,小写标签名称被认为是HTML标签。但是,带小点(属性访问器)的小写标签名不是。

  • 编译为React.createElement('component')(html标签)
  • 编译 React.createElement(Component)
  • <obj.component /> 编译 React.createElement(obj.component)

具体

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant