Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/427.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 基于聚焦的输入显示元素_Javascript_Reactjs - Fatal编程技术网

Javascript 基于聚焦的输入显示元素

Javascript 基于聚焦的输入显示元素,javascript,reactjs,Javascript,Reactjs,我正在努力使一段代码更有效率。其概念是,当您聚焦文本区域时,会显示一个段落标记,告诉您剩余的字符。目前我有: import React, { Component } from "react"; class Idea extends Component { state = { showCharactersRemaining: false }; calculateRemaining() { return 15 - this.props.body.length; }

我正在努力使一段代码更有效率。其概念是,当您聚焦文本区域时,会显示一个段落标记,告诉您剩余的字符。目前我有:

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;
import React,{Component}来自“React”;
类思想扩展了组件{
状态={
ShowCharacters保留:false
};
计算器维护(){
返回15-this.props.body.length;
}
onTextAreaFocus=()=>{
this.setState(state=>{
返回{showCharactersRemaining:true};
});
};
onBlur=()=>{
this.setState(state=>{
返回{showCharactersRemaining:false};
});
};
render(){
const{title,body}=this.props;
const{showCharactersRemaining}=this.state;
返回(
{showCharactersRemaining&&(
{this.calculaterMaining()}个剩余字符

)} ); } } 输出缺省思想;

它的工作,但也依赖于有两种方法附加到所说的文本区域,使其工作。有没有一种更聪明的方法来应对这种情况呢?

CSS可以为您处理它,省去了状态和事件处理程序的必要性。运行代码段以查看其工作情况(我删除了计数字符的逻辑以保持此示例的简单性)

.charcount{
显示:无;
}
text区域:焦点+.charcount{
显示:块;
}

剩余XX个字符