2016-09-18 144 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這樣我就可以清理代碼,但我真的不知道怎麼樣。任何幫助將不勝感激

+0

'this.ref.text.value'有什麼問題? – Li357

+0

有沒有問題,我只想學習如何用變量替換它 –

+0

你的意思是這樣的:'var val = this.ref.text.value;''?然後:'text:val' – Li357

回答

0

您可以只使用一個變量來存儲值和到位的this.refs.text.value使用它:

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