gpt4 book ai didi

javascript - 如何突出显示带有红色边框的空必填(*)输入字段,单击React中的按钮?

转载 作者:行者123 更新时间:2023-12-03 00:22:25 25 4
gpt4 key购买 nike

在下面的图片屏幕截图中,我将字段设置为必填字段,因此单击注册按钮如果有任何字段,那么我想在 React 中用红色边框突出显示该空字段,这怎么可能? ( https://blueprintjs.com/docs/#core/components/text-inputs )

form

constructor(props) {
super(props);
this.state = {
firstName: '',
lastName: '',
email: '',
password: '',
};
this.handleChange = this.handleChange.bind(this);
this.registerForm = this.registerForm.bind(this);
}

handleChange(event) {
this.setState({[event.target.name]: event.target.value});
}

registerForm(){
if(this.state.firstName.trim() && this.state.lastName.trim() &&
this.state.email && this.state.password){
console.log("registration successfully..!!");
}else{
console.log("all * marked fields mandatory");
}
}

render() {
return (
<div>
<h2>Fill Registration Details..!!</h2>
<InputGroup placeholder="Enter First Name...*"
name="firstName" value={this.state.firstName} onChange={this.handleChange}/>

<InputGroup placeholder="Enter Last Name...*" name="lastName"
value={this.state.lastName} onChange={this.handleChange}/>

<InputGroup placeholder="Enter your email...*" name="email"
value={this.state.email} onChange={this.handleChange}/>

<InputGroup placeholder="Enter your password...*"name="password"
value={this.state.password} onChange={this.handleChange}/>

<Button intent="Primary" onClick={this.registerForm}>Register</Button>
</div>
)
}

最佳答案

正如 @Saraband 所说,一种解决方案是根据输入字段是否包含错误来修改节点的类名:

<InputGroup
placeholder="Enter your password...*"
name="password"
className={this.state.password.length ? '' : 'error'}
value={this.state.password}
onChange={this.handleChange}
/>

然后您可以将其与以下 CSS 一起使用,该 CSS 将显示红色边框(例如):

.error input
{
border-bottom: 1px solid #eb516d;
}

另一种方法是使用 input 标记的原生 required 属性,但此方法很难自定义:

<input type='text' required/>

https://www.w3schools.com/tags/att_input_required.asp

关于javascript - 如何突出显示带有红色边框的空必填(*)输入字段,单击React中的按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54256701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com