ES6下React组件的相关写法

定义React组件、声明prop类型与默认prop、设置初始state、自动绑定

定义React组件

1
2
3
4
5
class Hello extends React.Component {
render() {
return <h1>Hello, {this.props.value}</h1>;
}
}

声明prop类型与默认prop

1
2
3
4
5
6
7
8
9
10
11
class Hello extends React.Component {
// ...
}
Hello.propTypes = {
value: React.PropTypes.string
};
Hello.defaultProps = {
value: 'world'
};

设置初始state

1
2
3
4
5
6
7
class Hello extends React.Component {
constructor(props) {
super(props);
this.state = {count: props.initialCount};
}
// ...
}

自动绑定

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class SayHello extends React.Component {
constructor(props) {
super(props);
this.state = {message: 'Hello!'};
// 这行很重要
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
alert(this.state.message);
}
render() {
// Because `this.handleClick` is bound, we can use it as an event handler.
return (
<button onClick={this.handleClick}>
Say hello
</button>
);
}
}
文章目录
  1. 1. 定义React组件
  2. 2. 声明prop类型与默认prop
  3. 3. 设置初始state
  4. 4. 自动绑定
|