I'm new to both JS and React and I'm working on a project for a bootcamp. I'm collaborating on a chat app and I wanted some insight on replacing strings with a variable to clean up the code. Here's what I'm working on:
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;
I'd like to replace this.refs.text.value
with a variable so I can clean up the code, but I'm not really sure how. Any help would be greatly appreciated
You can just use a variable to store the value and use it in place of 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 just uses a variable val
in place of this.refs.text.value
, although I would not recommend it because it doesn't necessarily make the code cleaner . Make sure not to change this.refs.text.value = '';
because if you do, you'll be reassigning the reference which is incorrect.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.