React event.preventDefault使用方法

event.preventDefault

定义和用法:
取消事件的默认动作

简单看一下下面代码:

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>
    );
  }
}

这是我重React官网doc中拿过来的 REACT

我们要注意看的就是 onSubmit部分的代码

handleSubmit 函数中可以看到添加了event.preventDefault();

这样的话我们会取消原有onSubmit中默认的效果,

效果是什么呢?就是在url中 带着 ‘?’ 转换页面的效果

猜你喜欢

转载自blog.csdn.net/weixin_43814775/article/details/107916632