1. 程式人生 > >1.2 增加一個新的react元件

1.2 增加一個新的react元件

src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import ClickCounter from './ClickCounter';
import registerServiceWorker from './registerServiceWorker';
import './index.css';

ReactDOM.render(<ClickCounter />, document.getElementById('root'));
registerServiceWorker();

src/ClickCounter.js

import React,{Component} from 'react';
class ClickCounter extends Component{
  constructor(props){
    super(props);
    this.onClickButton = this.onClickButton.bind(this);
    this.state = {count:0};
  }
onClickButton(){
  this.setState({count:this.state.count+1});
}

render(){
  return
( <div> <button onClick ={this.onClickButton}> Click Me</button> <div> Click Count:{this.state.count} </div> </div> ); } } export default ClickCounter;