首页 > 解决方案 > 单击表单字段时显示额外的文本 - 反应

问题描述

我正在制作一个响应表单,当前当单击该字段时,它会添加一个蓝色边框(我想保留它),但我想在下面显示一些额外的文本,我不知道该怎么做?

基本上,我有一个名字字段,当单击它时,我希望“输入您的名字”出现在该字段下方。

这是我目前拥有的:

<div className="form-group form-row">
    <label
       id="firstNameLabel"
       className="col-md-2 col-form-label text-md-right"
       htmlFor="firstName1"
       readOnly
    >
      First Name*
    </label>
    <div className="col-md-10">
         <input
         type="text"
         className="form-control"
         name="firstName1"
         ref="firstName1"
         placeholder="First Name"
         value={this.state.firstName1} 
         onChange={this.handleChange} 
         required
     />
     <div className="error" id="firstnameError" />
   </div>
 </div>

标签: javascripthtmlcssreactjsforms

解决方案


它是这样的:

如果您想观看,请在状态中存储一些标志,例如

this.setState({userClicked:true})

您想观看的事件可能是onFocus,即

<input
     type="text"
     className="form-control"
     name="firstName1"
     ref="firstName1"
     placeholder="First Name"
     value={this.state.firstName1} 
     onFocus={()=>{ this.setState({userClicked:true}) }}
     onChange={this.handleChange} 
     required
   />

您还可以使用onBlur将标志设置为 false,当输入失去焦点时,然后在渲染中将下面的代码放在您希望通知出现的位置:

....
{this.state.userClicked && <div>Enter first name</div>}

上面的行将确保在userClicked为 true 时呈现 div。


推荐阅读