Reactjs - 表单验证

时间:2017-11-30 10:20:37

标签: reactjs validation

任何人都可以帮助我,我真的在React中遇到验证表格,我也尝试过一些库,但我做错了。 我想验证两者都是必需的,数字是数字。

class Hello extends React.Component {
constructor() {
    super();
    this.state = {
      firstname: '',
      number: '',
    };
  }

  onChange = (event) => {
    this.setState({ [event.target.name]: event.target.value });
  }

  onSubmit = (event) => {
    event.preventDefault();
    console.log('Submited');
  }
  render() {
    return (
        <div>

        <form className="form-horizontal" onSubmit={this.onSubmit}>
          <div className="form-group">
            <label className="col-sm-2 control-label">Name</label>
            <div className="col-sm-10">
              <input type="text" name="firstname" className="form-control" onChange={this.onChange} placeholder="Firstname" />
            </div>
          </div>
          <div className="form-group">
            <label className="col-sm-2 control-label">Number</label>
            <div className="col-sm-10">
              <input type="text" name="number" className="form-control" onChange={this.onChange} placeholder="Number" />
            </div>
          </div>
          <div className="form-group">
            <div className="col-sm-offset-2 col-sm-10">
              <button type="submit" className="btn btn-success">Submit</button>
            </div>
          </div>
        </form>

        <h3>{this.state.firstname}</h3>
        <h3>{this.state.number}</h3>

      </div>
    );
  }
}

0 个答案:

没有答案