反应:将event.preventDefault()方法添加到功能组件中

时间:2018-10-12 22:04:03

标签: javascript reactjs

当前,我试图通过向功能组件(在bookList.js中定义的preventDefault())的onClick处理程序中添加BookList调用来避免刷新页面。我知道我可以做到从类组件到功能。但是,有什么方法可以在preventDefault()的{​​{1}}事件处理程序中调用onClick

这是我的示例代码:

BookListElement.js

BookList

bookList.js

import React from 'react';
import { connect } from 'react-redux';
import BookList from '../components/bookList';
import { deleteBook } from '../store/actions/projectActions';

const BookListElement = ({books, deleteBook}) => {
  if(!books.length) {
    return (
      <div>
        No Books
      </div>
    )
  }
  return (
    <div>
      {Array.isArray(books) ? books.map(book => {
        return (
          <BookList book={book} deleteBook={deleteBook} key={book._id} />
        );
      }): <h1>something wrong.</h1>}
    </div>
  );
};

const mapStateToProps = state => {
  return {
    books: state.books
  };
};

const mapDispatchToProps = dispatch => {
  return {
    deleteBook: _id => {
      dispatch(deleteBook(_id));
    }
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(BookListElement);

action.js

import React, { Component } from 'react';

const styles = {
  borderBottom: '2px solid #eee',
  background: '#fafafa',
  margin: '.75rem auto',
  padding: '.6rem 1rem',
  maxWidth: '500px',
  borderRadius: '7px'
};

const BookList = ({ book: { author, publication, publisher, _id }, deleteBook }) => {
  return (
        <form>
          <div className="collection-item" style={styles} key={_id}>
            <h2>{author}</h2>
            <p>{publication}</p>
            <p>{publisher}</p>
            <button className="btn waves-effect waves-light" onClick={() => {deleteBook(_id)}}>
              <i className="large material-icons">delete_forever</i>
            </button>
         </div>
       </form>
  );
};

export default BookList;

reducer.js

export const deleteBookSuccess = _id => {
  return {
    type: DELETE_BOOK,
    payload: {
      _id
    }
  }
};

export const deleteBook = _id => {
  return (dispatch) => {
    return axios.delete(`${apiUrl}/${_id}`)
      .then(response => {
        dispatch(deleteBookSuccess(response.data))
      })
      .catch(error => {
        throw(error);
      });
  };
};

3 个答案:

答案 0 :(得分:2)

如果您不希望按钮触发表单提交,请在type="button"元素中添加button属性。

默认情况下,button提交表单(将type设置为submit)。 设置type="button"表示它没有默认行为。

<form>
  <button type="button">type button doesn't trigger refresh</button>
  <button>no type triggers refresh</button>
</form>

答案 1 :(得分:1)

需要在preventDefault上调用event方法。但是,在设置onClick处理程序的方式中,event不会传递给处理程序。

以下是解决此问题的方法(在bookList.js中):

import React from 'react';

const BookList = ({ book: { author, publication, publisher, _id }, deleteBook }) => {

  const handleClick = event => {
    event.preventDefault();
    deleteBook(_id);
  }

  return (
        <form>
          <div>
            <h2>{author}</h2>
            <p>{publication}</p>
            <p>{publisher}</p>
            <button onClick={ handleClick }>
              <i>delete_forever</i>
            </button>
         </div>
       </form>
  );
};

因此onClick将通过event(默认情况下),然后只需在该preventDefault上调用event,然后调用deleteBook

答案 2 :(得分:0)

我做了一个简单的插图(组件),其中一个click事件触发了重新加载,而另一个则没有。如果这对您不起作用,那么问题就出在另一个地方,意味着在另一个组件中(您未提供的代码段)。希望对您有所帮助,即使不是,将来也可能对某人有所帮助:)

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.preventDefault = this.preventDefault.bind(this);
    this.dontPrevent = this.dontPrevent.bind(this);
  }
  
  // handler recieves the `e` event object
  dontPrevent() {
    alert('This page will reload :)');  
  }
  
  preventDefault(e) {
    alert('Page will NOT reload');
    e.preventDefault();
  }
 
  
  render() {
    return (      
      <div>
        <form onSubmit={this.preventDefault}>
         <div>
          <h3>NO Reload Example</h3> 
          <p>
            <button>Submit</button>&nbsp;
          </p>
        </div>
       </form>
       <hr/>
       <form>
         <div>
          <h3>Reload Example</h3> 
          <p>
            <button onClick={this.dontPrevent}>Submit</button>
          </p>
        </div>
       </form>
      </div>
    );
  }
}

ReactDOM.render(
  <Example />,
  document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
  <div id="app"></div>