当前位置:网站首页>JSX基础
JSX基础
2022-08-05 05:13:00 【@前端攻城狮】
JSX基础
JSX 仅仅只是 React.createElement(component, props, ...children) 函数的语法糖。
如下:
<MyButton color="blue" shadowSize={2}>
Click Me
</MyButton>
会编译为:
React.createElement(
MyButton,// 此时MyButton是一个变量,所以作用域中必须存在该变量
{color: 'blue', shadowSize: 2},
'Click Me'
)
普通的HTML标签会将被当作字符串传入:
<div className="sidebar" />
// 编译为
React.createElement(
'div',
{className: 'sidebar'}
)
React元素类型
JSX 标签的第一部分指定了 React 元素的类型。
可以在JSX中使用点语法来表示组件,当你在一个模块中导出许多 React 组件时,这会非常方便:
import React from 'react';
const MyComponents = {
DatePicker: function DatePicker(props) {
return <div>Imagine a {props.color} datepicker here.</div>;
}
}
function BlueDatePicker() {
return <MyComponents.DatePicker color="blue" />;
}
用户自定义的组件必须以大写字母开头,JSX中使用小写开头的标签会被当作普通的HTML标签:
import React from 'react';
// 正确!组件需要以大写字母开头:
function Hello(props) {
// 正确! 这种 <div> 的使用是合法的,因为 div 是一个有效的 HTML 标签:
return <div>Hello {props.toWhat}</div>;
}
function HelloWorld() {
// 正确!React 知道 <Hello /> 是一个组件,因为它是大写字母开头的:
return <Hello toWhat="World" />;
}
如果需要动态决定React元素类型,不能直接使用表达式作为标签名,要首先将它赋值给大写字母开头的变量:
import React from 'react';
import { PhotoStory, VideoStory } from './stories';
const components = {
photo: PhotoStory,
video: VideoStory
};
function Story(props) {
// 错误!JSX 类型不能是一个表达式。
return <components[props.storyType] story={props.story} />;
}
function Story(props) {
// 正确!JSX 类型可以是大写字母开头的变量。
const SpecificStory = components[props.storyType];
return <SpecificStory story={props.story} />;
}
JSX的Props
有多种方式可以在 JSX 中指定 props的。
包裹在 {} 中的 JavaScript 表达式作为一个 prop:
<MyComponent foo={1 + 2 + 3 + 4} />
字符串:
<MyComponent message="hello world" />
// 或
<MyComponent message={'hello world'} />
Props默认值为true:
<MyTextBox autocomplete />
// 等价于
<MyTextBox autocomplete={true} />
使用展开运算符...,可以传递整个已定义的props对象:
function App1() {
return <Greeting firstName="Ben" lastName="Hector" />;
}
// 等价于
function App2() {
const props = {firstName: 'Ben', lastName: 'Hector'};
return <Greeting {...props} />;
}
可以选择只传递部分props:
const Button = props => {
// 除kind的其他props被传递给button,这里只传递了onClick和children属性
const { kind, ...other } = props;
const className = kind === "primary" ? "PrimaryButton" : "SecondaryButton";
return <button className={className} {...other} />;
};
const App = () => {
return (
<div>
<Button kind="primary" onClick={() => console.log("clicked!")}>
Hello World!
</Button>
</div>
);
};
JSX中的子元素
包含在开始和结束标签之间的 JSX 表达式内容将作为特定属性 props.children 传递给外层组件。
这些子元素可以是字符串,HTML元素,React元素,{}包裹的 JS 表达式等:
<MyComponent>Hello world!</MyComponent>
<MyComponent>
<h1>Hello</h1>
</MyComponent>
<MyContainer>
<MyFirstComponent />
<MySecondComponent />
</MyContainer>
JS表达式作为子元素,渲染一个列表:
function Item(props) {
return <li>{props.message}</li>;
}
function TodoList() {
const todos = ['finish doc', 'submit pr', 'nag dan to review'];
return (
<ul>
{todos.map((message) => <Item key={message} message={message} />)}
</ul>
);
}
React 组件也能够返回存储在数组中的一组元素:
render() {
// 不需要用额外的元素包裹列表元素!
return [
// 不要忘记设置 key :)
<li key="A">First item</li>,
<li key="B">Second item</li>,
<li key="C">Third item</li>,
];
}
函数作为子元素(不常用):
// 调用子元素回调 numTimes 次,来重复生成组件
function Repeat(props) {
let items = [];
for (let i = 0; i < props.numTimes; i++) {
items.push(props.children(i));
}
return <div>{items}</div>;
}
function ListOfTenThings() {
return (
<Repeat numTimes={10}>
{(index) => <div key={index}>This is item {index} in the list</div>}
</Repeat>
);
}
布尔类型、Null和Undefined作为子元素虽合法但将会被忽略:
// 以下渲染结果均相同
<div />
<div></div>
<div>{false}</div>
<div>{null}</div>
<div>{undefined}</div>
<div>{true}</div>
这有助于依据特定条件来渲染其他的 React 元素。
例如,在以下 JSX 中,仅当 showHeader 变量为 true 时,才会渲染 <Header /> 组件:
<div>
{showHeader && <Header />}
<Content />
</div>
不过这要确保&&之前的表达式总是布尔值(而非一些真值或假值,如0)。
边栏推荐
- [Software Exam System Architect] Software Architecture Design ③ Domain-Specific Software Architecture (DSSA)
- The role of the range function
- 周末作业-循环练习题(2)
- RDD和DataFrame和Dataset
- 【过一下8】全连接神经网络 视频 笔记
- Algorithms - ones and zeros (Kotlin)
- Matplotlib(一)—— 基础
- RL reinforcement learning summary (1)
- What field type of MySQL database table has the largest storage length?
- 第四讲 反向传播随笔
猜你喜欢

第四讲 back propagation 反向传播

SQL(二) —— join窗口函数视图

【过一下9】卷积

Detailed Explanation of Redis Sentinel Mode Configuration File

Error creating bean with name 'configDataContextRefresher' defined in class path resource

【过一下3】卷积&图像噪音&边缘&纹理

OFDM 十六讲 5 -Discrete Convolution, ISI and ICI on DMT/OFDM Systems

jvm three heap and stack

RL reinforcement learning summary (1)

软件设计 实验四 桥接模式实验
随机推荐
Distributed systems revisited: there will never be a perfect consistency scheme...
number_gets the specified number of decimals
Pycharm中使用pip安装第三方库安装失败:“Non-zero exit code (2)“的解决方法
「PHP8入门指南」PHP简明介绍
第二讲 Linear Model 线性模型
span标签和p标签的区别
『递归』递归概念与典型实例
RL强化学习总结(一)
UVA10827
判断语句_switch与case
【过一下15】学习 lstm的一周
SQL(一) —— 增删改查
"PHP8 Beginner's Guide" A brief introduction to PHP
学习总结week2_4
位运算符与逻辑运算符的区别
【过一下8】全连接神经网络 视频 笔记
【记一下1】2022年6月29日 哥和弟 双重痛苦
多线程查询结果,添加List集合
将照片形式的纸质公章转化为电子公章(不需要下载ps)
vscode+pytorch使用经验记录(个人记录+不定时更新)