jsx语法实际上是一种js语法糖,如下相等
<MyButton color="blue" shadowSize={2}>
Click Me
</MyButton>
React.createElement(
MyButton,
{color: 'blue', shadowSize: 2},
'Click Me'
)
因为jsx其实是调用React.createElement
,若想使用jsx语法,必须先导入React库
自定义的组件,必须大写开头,不然react解析认为是html自带标签,如果你定义标签时用的小写,你可以把这个小写的组件赋值给一个大写的变量,然后把这个大写的变量拿去render,因为react是解析render的字符串的大小写来判断是否是自定义的组件而不是变量的内容.
import React from 'react';
import { PhotoStory, VideoStory } from './stories';
const components = {
photo: photoStory,
video: VideoStory
};
function Story(props) {
// Correct! JSX type can be a capitalized variable.
const SpecificStory = components[props.storyType];
return <SpecificStory story={props.story} />;
}
指定prop
1 在组件中直接使用props,但是要使用{}包裹
<MyComponent foo={1 + 2 + 3 + 4} /> /
2 语句与循环不能用在jsx中, 可以在外部使用
function NumberDescriber(props) {
let description;
if (props.number % 2 == 0) {
description = <strong>even</strong>;
} else {
description = <i>odd</i>;
}
return <div>{props.number} is an {description} number</div>;
}
3 props默认为true
<MyTextBox autocomplete />
<MyTextBox autocomplete={true} />
4 ...
function App1() {
return <Greeting firstName="Ben" lastName="Hector" />;
}
function App2() {
const props = {firstName: 'Ben', lastName: 'Hector'};
return <Greeting {...props} />;
}
JSX Children
props.children
几乎记住 一点就可以
JSX 遇到<就渲染组件, 遇到{ 就渲染js表达式,无他了,对于js语句和for块不可以直接在jsx中使用