繁体   English   中英

使用变量代替字符串

[英]Using a variable in place of a string

我是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

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!
},

这只是使用变量val代替this.refs.text.value ,虽然我不推荐它,因为它不一定使代码更清晰 确保不要更改 this.refs.text.value = ''; 因为如果你这样做,你将重新分配不正确的引用。

暂无
暂无

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

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