2016-05-24 18 views
8

React sınıflarımı ES6'ya dönüştürmeye çalışıyorum, ancak bu işlemde zorluk yaşıyorum. görünüm oluştur.Kurucuda bağlanma, parametrelere nasıl geçilir

Şimdi, bir parametreyi gereken bir setstate olan, örneğin bir kök modülü varsa: customElement modülü içinde Sonra

<customElement updateMood={this.updateMood}></customElement> 

:

constructor() { 
    super(); 

    this.state = { 
     mood: "" 
    }; 

    this.updateMood(value) = this.updateMood.bind(this,value); 
} 

updateMood(value) { 
    this.setState({mood: value}); 
} 

Sonra bir bileşene bu işlevi geçmesi

constructor() { 
    super(); 
} 

update(e) { 
    this.props.updateMood(e.target.value); 
} 

ve

işlemek: Ben böyle bir şey var

<input onChange={this.update} /> 

Bu doğru yol mu? Devam etsin diye ;-(alamayan bu yana sözdizimi hatası olduğu için

+0

Sadece this.updateMood (value) = this.updateMood.bind öğesini (this, value); ve değiştirin. 'Not bunu sahne verirken bağla. – Vishwanath

+0

* "Bu doğru yol mu?" * Çalışmıyorsa muhtemelen değil: P İhtiyacınız olan tek şey this.updateMood = this.updateMood.bind (this); '. Nasıl çalıştığını daha iyi anlamak için '.bind' ve genel olarak işlevlerle ilgili belgeleri okumalısınız. Bunun React veya ES6 btw ile ilgisi yoktur. Bu kapsamlı cevap için bir milyon teşekkür –

cevap

6

Sen, bu this.updateMood(value) = this.updateMood.bind(this,value); inşaat kullanamaz.

Bu

class CustomElement extends React.Component { 
    constructor() { 
    super(); 
    this.update = this.update.bind(this); 
    } 

    update(e) { 
    this.props.updateMood(e.target.value); 
    } 

    render() { 
    return <input onChange={this.update} /> 
    } 
} 

class Parent extends React.Component { 
    constructor() { 
    super(); 

    this.state = { 
     mood: "" 
    }; 

    this.updateMood = this.updateMood.bind(this); 
    } 

    updateMood(value) { 
    this.setState({ mood: value }); 
    } 

    render() { 
    return <div> 
     <CustomElement updateMood={this.updateMood}></CustomElement> 
     <h1>{ this.state.mood }</h1> 
    </div> 
    } 
} 

Example gibi sorununuzu çözebilir

+2

, sen benim gün kurtardı! – user3611459

0

veya typescript kullanırken, babel ayarlarına bağlı olarak veya aşağıdaki aynı olması, fakat çok daha uygun yazmaktır/bakımını:

class Parent extends React.Component { 
    constructor() { 
    super(); 

    this.state = { 
     mood: "" 
    }; 
    } 

    updateMood = (value) => { 
    this.setState({ mood: value }); 
    } 
} 
İlgili konular