1. class創建組件
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
2. 聲明默認屬性
class Greeting extends React.Component {
// ...
}
Greeting.defaultProps = {
name: 'Mary'
};
3. 設置出事狀態
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {count: props.initialCount};
}
// ...
}
4. this綁定
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() {
// 由於 `this.handleClick` 已經綁定至實例,因此我們纔可以用它來處理點擊事件
return (
<button onClick={this.handleClick}>
Say hello
</button>
);
}
}
或目前還處於實驗性階段的 Babel 插件 Class Properties。
class SayHello extends React.Component {
constructor(props) {
super(props);
this.state = {message: 'Hello!'};
}
// 警告:這種語法還處於實驗性階段
// 在這裏使用箭頭函數就可以把方法綁定給實例:
handleClick = () => {
alert(this.state.message);
}
render() {
return (
<button onClick={this.handleClick}>
Say hello
</button>
);
}
}