[进阶指南] 深入 JSX( Day25 )

基本上,JSX 单纯只是 React.createElement(component, props, ...children) function 的一个语法糖。

指定 React Element 类型

记得在 什麽是 JSX 有提到过 JSX 会经过 Babel 编译。以下是关於 React 更多的细节。

React 必须在作用域内

  1. 使用 script 直接在 html 载入 React
  2. import React from 'react'。下面的例子可以看到, JSX 其实编译过後使用了 React.createElement 语法,所以必须载入 React Module。
ReactDOM.render(
  React.createElement("h1", null, "Hello Bable"),
  document.getElementById('root')
);

在 JSX 类型中使用点记法

使用 <XXX.YYY></XXX.YYY> component 写法

import React from 'react';

const MyComponents = {
  CoverImg: function CoverImg(props) {
    return <img src={props.src} alt="Girl in a jacket" width="500" height="600">;
  }
}

function BlueDatePicker() {
  return <MyComponents.CoverImg src="https://reurl.cc/NZ0kOk" />;
}

使用者定义的 Component 必须由大写字母开头

<hello></hello> //小写 tag 会被视为 html 标签

<Hello></Hello> //Component 定义应该以

在 Runtime 时选择类型

function PhotoStory(props) {
  return <h1>Hello Photo, {props.story}</h1>;
}

function VideoStory(props) {
  return <h1>Hello Video, {props.story}</h1>;
}

const components = {
  photo: PhotoStory,
  video: VideoStory
};

function Story(props) {
  // 正确!JSX 类型可以是大写字母开头的变数。
  const SpecificStory = components[props.storyType];
  return <SpecificStory story={props.story} />;
}

const element = (
  <div>
    <Story storyType="photo" story="Here I am!" />
  </div>
);
ReactDOM.render(
  element,
  document.getElementById('root')
);

Codepen

JSX 中的 Props

  • JavaScript 表达式作为 Props
<MyCounter figure={1 + 2 + 3 + 4} />
  • 字串字面值
<MyComponent message="hello world" />

<MyComponent message={'hello world'} />
  • Props 预设为 「True」
<Door isOpen /> // isOpne 为 true
  • 展开属性
// 使用 other 这样的预设字去展开内容
const Button = props => {
  const { kind, ...other } = props;
  const className = kind === "primary" ? "PrimaryButton" : "SecondaryButton";
  return <button className={className} {...other} />;
};

Codepen

以上今天

参考资料:
https://zh-hant.reactjs.org/docs/jsx-in-depth.html


<<:  用React刻自己的投资Dashboard Day24 - styled components

>>:  TypeScript | Type 研究心得纪录 1

利用Redlock演算法实现自己的分布式锁

前言 我之前有写透过 lock or CAS 来防治,Racing condition 问题,但如果...

资料库:什麽是 unsigned integer

前言 一开始在设计资料库时常常不确定那个 type 要怎麽设,也不知道什麽是 unsigned in...

【在厨房想30天的演算法】Day 03 那个时间复杂度会让人生变复杂吗?

Aloha!又是我少女人妻Uerica!话说这次有很多以前的朋友同学们一起参加铁人赛,,不但可以一起...

Vue-cli专案介绍

今天要介绍的是最後这个使用Vue-cli制作的专案,前面我们介绍了这个专案的router和vuex部...

Day. 28 Recover Binary Search Tree

Leetcode #99. Recover Binary Search Tree 简单来说二元树里面...