用箭头函数方式,这样就不用担心this的指向问题了
import React from 'react';
import ReactDOM from 'react-dom';
import 'font-awesome/css/font-awesome.min.css';
import './index.css';
import './index.scss';
class Component extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'Yuusuke',
age: 18
};
}
handleClick() {
this.setState({
age: this.state.age + 1
})
}
onValueChange(e){
this.setState({
age: e.target.value
})
}
render() {
return (
<div>
<h1>I am {this.state.name}</h1>
<p>I am {this.state.age} years old!</p>
<p><button onClick={ () => {this.handleClick}}>年龄加一</button></p>
<p><button onClick={ () => {this.handleClick()}}>年龄加一</button></p>
<p><button onClick={ (e) => {this.handleClick(e)}}>年龄加一</button></p>
<p><input type="text" onChange={(e) => {this.onValueChange(e)}}/></p>
</div>
);
}
}
ReactDOM.render(
<div>
<Component></Component>
</div>,
document.getElementById('app')
)
;