2016-09-18 35 views
1

私はJSとReactの両方に新しく、私はブートキャンプのプロジェクトに取り組んでいます。私はチャットアプリを使ってコラボレーションしています。コードを整理するために文字列を変数に置き換えることについていくつかの洞察が必要でした。文字列の代わりに変数を使用する

import React from 'react'; 

const Form = React.createClass({ 

    submit(e) { 
    e.preventDefault(); 
    this.props.messagesRef.push({ 
     text: this.refs.text.value, 
     time: Date.now(), 
     user: { 
     displayName: this.props.user.displayName, 
     photoURL: this.props.user.photoURL, 
     uid: this.props.user.uid, 
     }, 
    }); 
    this.refs.text.value = ''; 
    }, 

    render() { 
    return (
     <form className="form" onSubmit={this.submit}> 
    <input className="form-input" placeholder="Write  something…" ref="text"/> 
     <button className="form-button">Send</button> 
     </form> 
    ); 
    } 
}); 
export default Form; 

私は、コードをクリーンアップすることができるように変数にthis.refs.text.valueを交換したいのですが、私はどのように本当にわからない。ここでは、私が働いているものです。すべてのヘルプは非常にあなただけの値を格納し、this.refs.text.valueの代わりにそれを使用する変数を使用することができます

+0

'this.ref.text.value'の問題は何ですか? – Li357

+0

それに問題はありません、変数に置き換える方法を学びたいだけです –

+0

このような意味です: 'var val = this.ref.text.value;'?そして次に: 'text:val' – Li357

答えて

0

をいただければ幸いです。

submit(e) { 
    e.preventDefault(); 
    var val = this.refs.text.value; 

    this.props.messagesRef.push({ 
    text: val, //notice the use of val 
    time: Date.now(), 
    user: { 
     displayName: this.props.user.displayName, 
     photoURL: this.props.user.photoURL, 
     uid: this.props.user.uid, 
    }, 
    }); 
    this.refs.text.value = ''; //do not use val here! 
}, 

これはちょうど私はあろうが、this.refs.text.valueの代わりに変数valを使用していますコードを作成する必要はありません。クリーナーを変更しないようにしてください。this.refs.text.value = '';これを行うと、間違った参照を再割り当てすることになります。

+0

多くの感謝アンドリュー! –

+0

問題がない@TylerSchmidt私が助けてくれたら、答えを受け入れることを検討してください:) – Li357

関連する問題