Reactを触る機会があったので、Reactについて、調べてみた。
677 views
Reactの内部で持つことができるミュータブルな値のこと
propsと違って、「後から値の変更ができる。」
クラスコンポーネントでのみ、使用できる。
import React, { Component } from 'react';
const App = ()=> (<Counter></Counter>)
class Counter extends Component{
constructor(props) {
super(props)
this.state = {yesCount:0 , noCount:0}
}
addCountNo = () =>{
this.setState({noCount:this.state.noCount + 1})
}
addCountYes = () => {
this.setState({yesCount:this.state.yesCount + 1})
}
render(){
return(
<div>
<div>Yesを押した回数 {this.state.yesCount}</div>
<div>Noを押した回数 {this.state.noCount}</div>
<button onClick = {this.addCountYes} >Yes</button>
<button onClick = {this.addCountNo}>No</button>
</div>
)
}
}
export default App;
ポイントは、「constructor」「setState」
「constructor」=>Stateの初期値を決めるのに必要
「setState」=>Stateの値を変更するのに必要
addCountNo = () =>{
this.state.noCount +=1
}
setState使わず、表現しようとすると動かないので要注意。
yesをクリックすると、、、
値が更新される
Page 5 of 7.
owl
駆け出しエンジニア
だいたいweb系をかじってる
最近ちょとブロックチェーンに興味出てきた