Javascript Maxlength 不起作用 React Js
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51161510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Maxlength does not work React Js
提问by MKOT
I have an input with React, but maxlengthdoes not work. Does anyone know how to solve this?
我有一个 React 输入,但maxlength不起作用。有谁知道如何解决这个问题?
This is handleChangeInput
这是 handleChangeInput
handleChangeInput(input) {
this.setState({
...this.state,
form: {
...this.state.form,
[input.target.name]: input.target.value
}
})
}
And this is my input:
这是我的输入:
<div className="input-field col s12 m6 l6">
<input onChange={this.handleChangeInput} value={this.state.form.message} type="text" className="phone validate" name="phone" maxlength="11"/>
<label for="telefone">Telefone</label>
</div>
回答by Tholle
Property and attribute names are generally camelCasein React, maxLengthworks.
属性和属性名称通常camelCase在 React 中,maxLength有效。
<input
onChange={this.handleChangeInput}
value={this.state.form.message}
type="text"
className="phone validate"
name="phone"
maxLength="11"
/>
However, you can still override this option if you give the input a valuelonger than maxLength. The only way around this is to check the length of the valuein the callback, and truncate it.
但是,如果输入的value长度超过maxLength. 解决此问题的唯一方法是检查value回调中的 长度,并将其截断。
Example
例子
class App extends React.Component {
state = { form: { message: "" } };
handleChangeInput = event => {
const { value, maxLength } = event.target;
const message = value.slice(0, maxLength);
this.setState({
form: {
message
}
});
};
render() {
return (
<input
onChange={this.handleChangeInput}
value={this.state.form.message}
type="text"
className="phone validate"
name="phone"
maxLength="11"
/>
);
}
}
回答by Micah Friedland
for maxLength to work, type has to be 'text' (most people are probably putting number)
要使 maxLength 起作用,类型必须是“文本”(大多数人可能都在输入数字)
回答by Chirag Shah
You need to pass maxLength value as a number.
您需要将 maxLength 值作为数字传递。
<input
onChange={this.handleChangeInput}
value={this.state.form.message}
type="text"
className="phone validate"
name="phone"
maxLength={11}
/>
回答by aakash sharma
inputProps = {{maxLength:6}}
variant="outlined"


