React

009|React之JSX In Depth

2017-06-06  本文已影响11人  中年小钢炮

使用import导入其它文件中的component:

import React from 'react';
import CustomButton from './CustomButton';

可以使用dot-notation来引用component:

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" />;
}

自定义组件首字母必须大写:

import React from 'react';

// Wrong! This is a component and should have been capitalized:
function hello(props) {
  // Correct! This use of <div> is legitimate because div is a valid HTML tag:
  return <div>Hello {props.toWhat}</div>;
}

function HelloWorld() {
  // Wrong! React thinks <hello /> is an HTML tag because it's not capitalized:
  return <hello toWhat="World" />;
}

可以通过变量引用组件:

  // Wrong! JSX type can't be an expression.
  return <components[props.storyType] story={props.story} />;

  // Correct! JSX type can be a capitalized variable.
  const SpecificStory = components[props.storyType];
  return <SpecificStory story={props.story} />;

props默认为true:

<MyTextBox autocomplete />

<MyTextBox autocomplete={true} />

使用spread语法来赋值,例如下面两个段代码效果是一样的:

function App1() {
  return <Greeting firstName="Ben" lastName="Hector" />;
}

function App2() {
  const props = {firstName: 'Ben', lastName: 'Hector'};
  return <Greeting {...props} />;
}

可以将函数作为children,通过props.children来引用:

// Calls the children callback numTimes to produce a repeated component
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>
  );
}

React中什么是Uncontrolled Component?

好,这一节就到这里。后续我将介绍更多React技术细节,来慢慢解答上述问题。

想学计算机技术吗?需要1对1专业级导师指导吗?想要团队陪你一起进步吗?欢迎加我为好友!微信号:iTekka。

上一篇 下一篇

猜你喜欢

热点阅读