2016-09-18 65 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