maxLength in Reactjs



假设以下代码:

class Button extends React.Component{
	render(){
return(
<button 
onClick = {() => this.props.handleInput(this.props.value)} 
value = {this.props.value}>
{this.props.value}
</button>
)
}
}
class TodoApp extends React.Component {
constructor(props) {
super(props)
this.state = {
	input: ''
}
this.handleInput = this.handleInput.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
}

handleInput(value){
	this.setState( state => ({
input: state.input += value
}))
}
	handleInputChange(event){
const {value, maxLength} = event.target;
const limitedMessage = value.slice(0,maxLength)
this.setState({
	input: limitedMessage
})
}


render() {
return (
<div>
<input
onChange = {this.handleInputChange}
type = 'text' 
value = {this.state.input}
maxLength = '3'
/>
<Button handleInput = {this.handleInput} value = '1' />
<Button handleInput = {this.handleInput} value = '2' />
<Button handleInput = {this.handleInput} value = '3' />
<Button handleInput = {this.handleInput} value = '4' />
<Button handleInput = {this.handleInput} value = '5' />
</div>
)
}
}
ReactDOM.render(<TodoApp />, document.querySelector("#app"))

我不确定为什么maxLength不适用于更新显示文本框值状态的按钮。当我在文本框中键入时,正在管理maxLength。我做了一个小提琴来演示我在说什么。

https://jsfiddle.net/rtlatelpa/dxr4ycsj/

您还应该像在handleInputChange中那样处理handleInput中的文本的最大长度。

handleInput(value) {
let { input } = this.state;
input += value
this.setState(state => ({
input: input.slice(0, 3)
}))
}

这是正在工作的jsFiddle

希望有帮助:(

因为在这个函数中:

handleInput(value){
this.setState( state => ({
input: state.input += value
}))
}

您忘记检查maxLength,所以它在任何情况下都会将value附加到state.input

最新更新