创建
- ES6 方式
```typescript
import React from ‘react’;
class MyComponent extends React.Component {
constructor(props) {
} render() {super(props);
} }return ( <div>Hi</div> )
export default MyComponent;
- ES5 方式:已过时,不支持 class,支持 IE8
```typescript
import React from 'react';
const MyComponent = React.createClass({
render() {
return ( <div>Hi</div> )
}
})
props
接收外部数据
接收外部函数
只读不写
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {n: 0}
}
onClick = () => { this.setState({ n: this.state.n + 1 }); }
render() {
return (<Son n={this.state.n} onClick={this.onClick}>Hi</Son>)
}
}
class Son extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
{this.props.n} <button onClick={this.props.onClick}>+1</button>
<div>
{this.props.children}
</div>
</div>
)
}
}
state
setState 的 shallow merge : React 只会检查新 state 和旧 state 第一层的区别,并把新 state 缺少的数据从旧 state 里拷贝过来