方法一:
class Demo extends React.Component {
constructor() {
......
}
// static是es6的语法
static defaultProps = {
age: 20
}
render() {
return (<div> the age is { this.props.age } </div>)
}
}
ReactDOM.render(<Demo />, document.getElementById('root'))
方法二:
class Demo extends React.Component {
constructor() {
......
}
render() {
return (<div> the age is { this.props.age } </div>)
}
}
Demo.defaultProps = {
age: 20
}
ReactDOM.render(<Demo />, document.getElementById('root'))
方法一:
class Demo extends React.Component {
constructor() {
super();
this.state = {
count: 0,
time: (new Date()).toLocaleTimeString()
}
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
alert(this.state.count)
}
render() {
return (<div onClick={this.handleClick}> this time is { this.state.time } </div>)
}
}
ReactDOM.render(<Demo />, document.getElementById('root'));
方法二:
class Demo extends React.Component {
constructor() {
super();
this.state = {
count: 0,
time: (new Date()).toLocaleTimeString()
}
}
handleClick() {
alert(this.state.count)
}
render() {
return (<div onClick={this.handleClick.bind(this)}> this time is { this.state.time } </div>)
}
}
ReactDOM.render(<Demo />, document.getElementById('root'));
方法三:
class Demo extends React.Component {
constructor() {
super();
this.state = {
count: 0,
time: (new Date()).toLocaleTimeString()
}
}
handleClick() {
alert(this.state.count)
}
render() {
return (<div onClick={() => {this.handleClick}}> this time is { this.state.time } </div>)
}
}
ReactDOM.render(<Demo />, document.getElementById('root'));
方法四:
class Demo extends React.Component {
constructor() {
super();
this.state = {
count: 0,
time: (new Date()).toLocaleTimeString()
}
}
// 这里的handleClick是一个属性,代表一个匿名函数,通过this.handleClick可以访问到这个属性值,也就是这个匿名函数
handleClick = () => {
alert(this.state.count)
}
render() {
return (<div onClick={this.handleClick}> this time is { this.state.time } </div>)
}
}
ReactDOM.render(<Demo />, document.getElementById('root'));
this.handleClick.bind(this)
会生成新的函数(this.handleClick !== this.handleClick.bind(this),bind方法会返回新的函数),所以方法二和方法三不推荐使用,性能不好,每次渲染都会生成新的函数。方法一和方法三都可以。