State React’ın ne güçlü özelliklerinden biridir. Değişebilecek değerleri tutar. Sadece Class componentlerde kullanılır. State’lerde değişiklik yapıldığında ilgili yer tekrar render edilir. Böylece arayüzdeki değerlerde değişir. Şimdir bir örnekle state oluşturalım ve bunu güncelleyelim. State’i değiştirmek için setState kullanmak gerekiyor ve state tanımlayarak başlanmalı.
“Hoş Geldiniz” yazan state’i butona tıklayınca “Derinkod.com” olarak güncelliyoruz.
class OrnekComponent extends React.Component { constructor(props) { super(props); this.state = { name: 'Hoş Geldiniz' }; this.handleClick = this.handleClick.bind(this); } handleClick() { this.setState({ name:'Derinkod.com' }) } render() { return ( <div> <button onClick={this.handleClick}>Değiştir</button> <h1>{this.state.name}</h1> </div> ); } };
***Gelin bir de sayaç örneği yapalım***
increment ile +1 decrement ile -1 reset ile 0 yapacağız.
class Counter extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; this.increment = this.increment.bind(this) this.decrement = this.decrement.bind(this) this.reset = this.reset.bind(this) } increment(){ this.setState(state => ({ count : state.count + 1 })) } decrement(){ this.setState(state => ({ count : state.count - 1 })) } reset(){ this.setState(state => ({ count : 0 })) } render() { return ( <div> <button className='inc' onClick={this.increment}>Increment!</button> <button className='dec' onClick={this.decrement}>Decrement!</button> <button className='reset' onClick={this.reset}>Reset</button> <h1>Current Count: {this.state.count}</h1> </div> ); } };
***Birde kontrollü form örneği yapalım***
bir inputa yazdığımız değerleri butona tıkladığımızda h1 etiketinde gösterelim.
class MyForm extends React.Component { constructor(props) { super(props); this.state = { input: '', submit: '' }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { this.setState({ input: event.target.value }); } handleSubmit(event) { event.preventDefault(); this.setState({ submit:this.state.input }) } render() { return ( <div> <form onSubmit={this.handleSubmit}> <input value={this.state.input} onChange={this.handleChange} /> <button handleSubmit={this.handleSubmit} type='submit'>Submit!</button> </form> <h1>{this.state.submit}</h1> </div> ); } };
*** Birde && koşullu örnek yapalım ***
Butona bastığımızda h1 etiketinde açık yazan yazıyı gizleyeceğiz
class MyComponent extends React.Component { constructor(props) { super(props); this.state = { display: true } this.toggleDisplay = this.toggleDisplay.bind(this); } toggleDisplay() { this.setState(state => ({ display: !state.display })); } render() { return ( <div> <button onClick={this.toggleDisplay}>GİZLE</button> {this.state.display && <h1>Açık!</h1>} </div> ); } };