如何处理 React 表单字段中的空值?
How to handle empty value in React form fields?
以下代码摘自reactjs.org,我的问题是如何处理下面代码中的空值。只有当用户有一些输入时才会触发警报,如果输入为空则不应触发
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
ReactDOM.render(
<NameForm />,
document.getElementById('root')
);
您应该在 handleSubmit
函数中使用 if 语句
handleSubmit(event) {
if(this.state.value){
alert('A name was submitted: ' + this.state.value);
}
event.preventDefault();
}
这样,如果值等于 ''
,则不会显示警报,如果它包含任何字符,例如 'm'
,它将显示警报
以下代码摘自reactjs.org,我的问题是如何处理下面代码中的空值。只有当用户有一些输入时才会触发警报,如果输入为空则不应触发
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
ReactDOM.render(
<NameForm />,
document.getElementById('root')
);
您应该在 handleSubmit
函数中使用 if 语句
handleSubmit(event) {
if(this.state.value){
alert('A name was submitted: ' + this.state.value);
}
event.preventDefault();
}
这样,如果值等于 ''
,则不会显示警报,如果它包含任何字符,例如 'm'
,它将显示警报