简体   繁体   English

在 React 中将文本区域的最大长度限制为 100

[英]Restrict text area max length to 100 in React

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

How to restrict text area length to 100 chars in react.如何在反应中将文本区域长度限制为 100 个字符。

You should allow value updating but not directly, as you want to add a restriction to it.您应该允许值更新,但不能直接允许,因为您想对其添加限制。 So:所以:

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}
/>;

您可以使用 JSX maxLength 属性作为 maxLength="100"

Assuming event is the new value and this.changeHandler is the state updater, you could do something like this:假设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} />

This will cap the <textarea> character limit to 100 characters.这会将<textarea>字符限制上限为 100 个字符。

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

We have to specify attribute like maxLength={100}, then it worked.我们必须指定像 maxLength={100} 这样的属性,然后它就起作用了。

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

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