我正在使用TextField组件捕获电话号码。在用户键入时,如果该输入不是数字或未遵循格式并显示errorText,则我想使该输入无效。当前,即使不触摸该字段也会显示errorText。我该如何实现这种行为?
任何帮助是极大的赞赏。
扩展Larry答案,将errorText设置为状态下的属性(以下示例中的errorText)。当TextField中的值更改时,验证条目并设置属性(errorText)的值以显示和隐藏错误。
class PhoneField extends Component
constructor(props) {
super(props)
this.state = { errorText: '', value: props.value }
}
onChange(event) {
if (event.target.value.match(phoneRegex)) {
this.setState({ errorText: '' })
} else {
this.setState({ errorText: 'Invalid format: ###-###-####' })
}
}
render() {
return (
<TextField hintText="Phone"
floatingLabelText="Phone"
name="phone"
errorText= {this.state.errorText}
onChange={this.onChange.bind(this)}
/>
)
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句