Day 1

作者: 云彩上的翅胖 | 来源:发表于2017-02-13 22:28 被阅读0次

JSX

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

//一个元素
const element = (
  <h1 className="greeting">
    Hello, world!
  </h1>
);

//编译时调用`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 <h1>Hello, {props.name}</h1>;
}

类组件

class Welcome extends React.Component {
    constructor(props){
        super(props);
        //...
    }
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

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

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

props对象

定义

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

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Sara" />;
//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

      本文链接:https://www.haomeiwen.com/subject/qubtwttx.html