import React from 'react'
class App extends React.Component{
constructor(props){
super(props)
this.state = {
num:1
}
}
handleClick(){
this.setState({
num:this.state.num+1
})
}
render(){
return(
<div>
<h2>App</h2>
<button onClick={this.handleClick.bind(this)}>b1</button>
<button onClick={()=>this.handleClick()}>b2</button>
</div>
)
}
}
export default App;
1 == 1 //true
{c:1} == {c:1} //这种情况下是false,因为每次生成的对象,存入到内存的地址是不同的
import React from 'react'
class App extends React.Component{
constructor(props){
super(props)
this.state = {
num:1
}
this.handleClick = this.handleClick.bind(this)
}
handleClick(){
this.setState({
num:this.state.num+1
})
}
render(){
return(
<div>
<h2>App</h2>
<button onClick={this.handleClick}>b1</button>
</div>
)
}
}
export default App;
这样就是通过在构造函数里声明。不会在每次render的时候重复生成。这个是因为类通过构造函数实例化,在constructor里进行绑定,只用生成一次,后面就可以直接调用。
import React from 'react'
class App extends React.Component {
constructor(props){
super(props)
this.state={
num:1,
title:'tyrmars',
name:'zhang'
}
this.handleClick = this.handleClick.bind(this)
}
handleClick(){
this.setState({
num:this.state.num+1
})
}
render() {
const
return (
<div>
<h2>I am App</h2>
<button onClick={this.handleClick}>b1</button>
<Demo style={{color:'red'}} title={this.state.title}></Demo>
</div>
)
}
}
class Demo extends React.Component {
render() {
return (<h2>I am Demo</h2>)
}
}
export default App
<Demo style={{color:'red'}} title={this.state.title}></Demo>
<Demo {...this.state}></Demo>