注意点
- 本质上来讲,JSX 只是为 React.createElement(component, props, ...children) 方法提供的语法糖,JSX不止一行时,请用小括号包裹
- 可以使用 JSX 中的点表示法来引用 React 组件。你可以方便地从一个模块中导出许多 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" />;
}
应用联想:一个组件如果有多种状态,且每种状态不太好复用,可以用这种方式做成多个组件
- 自定义组件首字母大写,内置组件(即html标签)小写
- 在运行时选择类型
不能使用表达式来作为 React 元素的标签。如果你的确想通过表达式来确定 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} />;
}
- 属性取值(虽有多种方式,但建议统一使用{ 表达式 }取值)
1、JS表达式(不能使用if和for循环,因为他们不是表达式)
2、字符串常量
<MyComponent message="<3" />
<MyComponent message={'<3'} />
3、默认为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} />; // 会把所有属性都传给子组件,造成子组件属性混乱
}
- 布尔值、Null 和 Undefined 被忽略
false、null、undefined 和 true 都是有效的子代,但它们不会直接被渲染。你必须先把它转换成字符串
<div>
My JavaScript variable is {String(myVariable)}.
</div>
- 确保 && 前面的表达式始终为布尔值
// 当 props.message 为空数组时,它会打印0
<div>
{props.messages.length &&
<MessageList messages={props.messages} />
}
</div>
// 正确
<div>
{props.messages.length > 0 &&
<MessageList messages={props.messages} />
}
</div>
网友评论