1

下面的代码取自 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')
);
4

1 回答 1

1

handleSubmit你应该在你的函数中使用 if 语句

  handleSubmit(event) {
   if(this.state.value){
    alert('A name was submitted: ' + this.state.value);
   }
    event.preventDefault();
  } 

这样,如果 value 等于''alert 则不会显示,如果它包含任何字符,例如'm'它会显示警报

于 2021-01-25T16:01:01.300 回答