gpt4 book ai didi

javascript - 将 : Adding event. preventDefault() 方法 react 到功能组件中

转载 作者:行者123 更新时间:2023-11-30 11:13:10 27 4
gpt4 key购买 nike

目前,我试图通过将 preventDefault() 调用添加到功能组件 (BookList) 的 onClick 处理程序中来避免刷新页面在 bookList.js 中定义)。我知道我可以从类组件到功能。但是,有没有办法在 BookListonClick 事件处理程序中调用 preventDefault()

这是我的示例代码:

BookListElement.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);

bookList.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;

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

reducer.js

case DELETE_BOOK:
let afterDelete = state.filter(book => {
return book._id !== action.payload._id
});
return afterDelete;

最佳答案

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

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

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

关于javascript - 将 : Adding event. preventDefault() 方法 react 到功能组件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52787539/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com