Day 1

JSX

JSX描述了一个对象,使用babel编译JSX时会调用React.createElement()方法,该方法会对输入做一些错误检验并最终返回一个JS对象。这种用JSX书写的对象被称为** React元素 **。

//一个元素
const element = (
  

Hello, world!

); //编译时调用`React.createElement()`方法 const element = React.createElement( 'h1', {className: 'greeting'}, 'Hello, world!' ); //最终返回的对象(与真正返回的对象相比结构有所简化) const element = { type: 'h1', props: { className: 'greeting', children: 'Hello, world' } };

React元素

React元素是一个对象,元素被用来描述一个组件的实例或者一个DOM节点以及它们的属性值。元素含有的信息包括组件的类型、组件的属性和该元素内部的子元素。

组件与属性

组件分为函数型组件与类组件

函数型组件

创建组件的最简单方法是定义一个JS函数,这个函数应接受一个对象(props)作为参数并且返回一个React元素。

function Welcome(props) {
  return 

Hello, {props.name}

; }

类组件

class Welcome extends React.Component {
    constructor(props){
        super(props);
        //...
    }
  render() {
    return 

Hello, {this.props.name}

; } }

React的角度看两种方式定义的组件是一样的。

调用constructor构造器时必须传入props

props对象

定义

当元素是一个用户自定义的组件时,React就会把JSX中描述的属性用一个对象传递给这个组件,这个对象叫做props

function Welcome(props) {
  return 

Hello, {props.name}

; } const element = ; //props==={ // name:'Sara' //} ReactDOM.render( element, document.getElementById('root') );

所有组件的名称首字母都应大写。
组件返回的元素必须有一个单独的根元素。

props是只读的

组件 ** 不允许 ** 修改props的值。

组件的状态与生命周期

state

stateprops类似,不同之处在于state是组件私有的,完全由组件自身控制。

setState()方法

直接在this.state上修改属性的值并不会重新绘制当前组件。

//wrong
this.state.date = new Date();

只有调用setState()方法才会重新绘制组件。

// Correct
this.setState({date: new Date()});

调用setState()方法时,Recat会把你提供的对象与现有的state对象合并。重名的属性会被更新,没有的属性会被添加。

setState()方法是异步调用的。

你可能感兴趣的:(Day 1)