简体   繁体   English

使用变量代替字符串

[英]Using a variable in place of a string

I'm new to both JS and React and I'm working on a project for a bootcamp. 我是JS和React的新手,我正在研究一个训练营的项目。 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. 我想用变量替换this.refs.text.value所以我可以清理代码,但我不确定如何。 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 : 您可以使用变量来存储值,并使用它来代替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 . 这只是使用变量val代替this.refs.text.value ,虽然我不推荐它,因为它不一定使代码更清晰 Make sure not to change this.refs.text.value = ''; 确保不要更改 this.refs.text.value = ''; because if you do, you'll be reassigning the reference which is incorrect. 因为如果你这样做,你将重新分配不正确的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM