react文档阅读笔记----JSX属性

来源:互联网 发布:怎么建数据库 编辑:程序博客网 时间:2024/06/15 01:37

JSX属性

.操作符在JSX中的应用

如果一个模块export出去多个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原有的标签重名。

不能使用[]

当对象的属性是变量的时候,我们通常使用[]来获取属性值,但是JSX中不支持这种表达式。要想获取到相应的组件,需要先用变量将组件获取到,然后再使用JSX表达式。

import React from 'react';import { PhotoStory, VideoStory } from './stories';const components = {  photo: PhotoStory,  video: VideoStory};function Story(props) {  // Wrong! JSX type can't be an expression.  return <components[props.storyType] story={props.story} />;}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} />;}

JSX属性值

  • 可以使用javascript表达式:

你可以使用javascript表达式作为JSX的属性值。只要包在{}中即可:

<MyComponent foo={1 + 2 + 3 + 4} />

对于MyComponent,属性props.foo的值为10。因为这是1+2+3+4的执行结果。

但是if语句和for循环这种并不是javascript表达式。但是你可以在外面使用它们,达到想要的效果。

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>;}
  • 字符串

字符串有两种书写方式:

<MyComponent message="hello world" /><MyComponent message={'hello world'} />

你可以直接设置属性,因为HTML的属性默认是字符串类型的,所以两种是等价的。

<MyComponent message="&lt;3" /><MyComponent message={'<3'} />


  • boolean值的属性

属性值默认是true,所以有以下两种表达方式:
<MyTextBox autocomplete /><MyTextBox autocomplete={true} />


  • 解构赋值属性

如果属性全都包含在一个对象里面,这时候你想传入到JSX中,你可以使用...传入。以下两种写法等价:
function App1() {  return <Greeting firstName="Ben" lastName="Hector" />;}function App2() {  const props = {firstName: 'Ben', lastName: 'Hector'};  return <Greeting {...props} />;}

你也可以挑选对象里面的一些属性处理过后再传入部分到JSX中:

const Button = props => {  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>  );};