先再創建一個App2.js 裡面程式碼打
import React, { Component } from 'react'
export default class App2 extends Component {
goClick(e){
console.log('觸發');
}
render() {
return (
<div>
<p>0</p>
<button onClick={this.goClick}>點我</button>
</div>
)
}
}
index.js 修改
import React from 'react';
import ReactDOM from 'react-dom';
// import './index.css';
import App from './App2';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
import React, { Component } from 'react'
export default class App2 extends Component {
constructor(props) {
super(props);
this.state = { gonum : 0 };
}
goClick(e){
// console.log('觸發');
this.setState({
gonum : this.state.gonum+1
})
}
render() {
return (
<div>
<p>{ this.state.gonum }</p>
<button onClick={this.goClick.bind(this)}>點我</button>
</div>
)
}
}
再react裡面它是每個組件都有一個狀態也就是state,跟寫JS&JQ不一樣的概念,操作狀態來改變畫面。
constructor(props) {
super(props);
this.state = {
自訂:自訂
};
}
constructor,super都是固定的寫法,需要背下來,這是react的構造函數
<button onClick={this.goClick.bind(this)}>點我</button>
goClick後面的bind(),是傳值把this傳到goClick()裡面
如果上面覺得很難背也沒關係,直接偷懶更簡單的方式
import React, { Component } from 'react'
export default class App2 extends Component {
state = {
gonum : 0
}
goClick(e){
this.setState({
gonum : this.state.gonum+1
})
}
render() {
return (
<div>
<p>{ this.state.gonum }</p>
<button onClick={this.goClick.bind(this)}>點我</button>
</div>
)
}
}
直接state甚麼構造函數都不用
import React, { Component } from 'react'
export default class App2 extends Component {
state = {
gonum : false
}
goClick(e){
this.setState({
gonum : !this.state.gonum
})
}
render() {
return (
<div>
<button onClick={this.goClick.bind(this)}>
{this.state.gonum ? 'No' : 'Yes'}
</button>
</div>
)
}
}
點擊後NO & YES 互相交換
import React, { Component } from 'react'
export default class App2 extends Component {
state = {
gonum : 0,
gonoyes:false
}
goClick(e){
this.setState({
gonum : this.state.gonum+1 ,
gonoyes : !this.state.gonoyes
})
}
render() {
return (
<div>
<p>{ this.state.gonum }</p>
<button onClick={this.goClick.bind(this)}>{this.state.gonoyes ? 'No' : 'Yes'}</button>
</div>
)
}
}