【问题标题】:Restrict text area max length to 100 in React在 React 中将文本区域的最大长度限制为 100
【发布时间】:2020-03-23 01:31:45
【问题描述】:
<textarea
  className="form-control round InputActive textarea"
  id="txtarea-dwip-service-description"
  name="ServiceDescription"
  value={model.ServiceDescription}
  onChange={event => this.changeHandler(event)}
/>;

如何在反应中将文本区域长度限制为 100 个字符。

【问题讨论】:

    标签: html reactjs text textarea maxlength


    【解决方案1】:

    您应该允许值更新,但不能直接允许,因为您想对其添加限制。所以:

    const [value, setValue] = useState('')
    
    const handleChange = (event) => {
      const shouldSetValue = value.length < 100
    
      if (shouldSetValue) setValue(event.target.value)
    }
    
    <textarea
      className="form-control round InputActive textarea"
      id="txtarea-dwip-service-description"
      name="ServiceDescription"
      value={model.ServiceDescription}
      onChange={handleChange}
    />;
    

    【讨论】:

      【解决方案2】:

      你可以使用 JSX 的 maxLength 属性为 maxLength="100"

      【讨论】:

        【解决方案3】:

        假设event 是新值,this.changeHandler 是状态更新器,您可以这样做:

         <textarea
            maxLength={10}
            className="form-control round InputActive textarea"
            id="txtarea-dwip-service-description"
            name="ServiceDescription"
            onChange={event => this.changeHandler(event)}
            value={model.ServiceDescription} />
        

        这会将 &lt;textarea&gt; 的字符数限制为 100 个字符。

        【讨论】:

          【解决方案4】:
                                      <textarea maxLength={100} className="form-control round InputActive textarea" id="txtarea-dwip-service-description"
                                          name="ServiceDescription" value={model.ServiceDescription} onChange={(event) => this.changeHandler(event)} 
                                          ></textarea>
          

          我们必须指定像 maxLength={100} 这样的属性,然后它才起作用。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-02-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-01-17
            • 1970-01-01
            • 1970-01-01
            • 2010-10-27
            相关资源
            最近更新 更多