根据输入的焦点显示元素

时间:2018-11-05 16:50:53

标签: javascript reactjs

我正在尝试使一段代码更有效率。其概念是,当您重点关注文本区域时,会看到一个段落标签,告诉您剩余的字符。目前,我有:

import React, { Component } from "react";

class Idea extends Component {
  state = {
    showCharactersRemaining: false
  };

  calculateRemaining() {
    return 15 - this.props.body.length;
  }

  onTextAreaFocus = () => {
    this.setState(state => {
      return { showCharactersRemaining: true };
    });
  };

  onBlur = () => {
    this.setState(state => {
      return { showCharactersRemaining: false };
    });
  };

  render() {
    const { title, body } = this.props;
    const { showCharactersRemaining } = this.state;
    return (
      <div className="idea">
        <input type="text" name="title" value={title} />
        <textarea
          rows="3"
          name="body"
          maxlength="15"
          value={body}
          onFocus={this.onTextAreaFocus}
          onBlur={this.onBlur}
        />
        {showCharactersRemaining && (
          <p>{this.calculateRemaining()} characters remaining.</p>
        )}
      </div>
    );
  }
}

export default Idea;

这是可行的,但还依赖于将两种方法附加到所述文本区域以使其起作用。有没有更聪明的方式来执行此操作?

1 个答案:

答案 0 :(得分:1)

CSS可以为您处理它,从而消除了使用状态和事件处理程序的必要性。运行该代码片段以查看其工作原理(为了使本示例简单易懂,我删除了计数字符的逻辑)

.charcount {
  display: none;
}

textarea:focus+.charcount {
  display: block;
}
<div className="idea">
  <textarea rows="3" name="body" maxlength="15" value="foo"></textarea>
  <p class="charcount">XX characters remaining.</p>
</div>