gpt4 book ai didi

javascript - 使用 onClick 时进行 React 渲染

转载 作者:行者123 更新时间:2023-12-03 04:36:13 28 4
gpt4 key购买 nike

想知道是否有办法可以在没有构造函数的情况下渲染组件。

下面是我的 onClick 代码。我的目标是当您单击按钮时进行渲染以使按钮消失。我不确定是否有办法在不创建的情况下渲染它

 constructor(props) {
super(props);
this.state = {}
}






<div>
<h1>Title: {post.title}</h1>
<h2>Pages: {post.pages}</h2>
<div>Reviews:</div>
<button
onClick={() => { this.props.addToMyPage(
{
userId: user.user.user_id,
bookId: post.book_id
}
)}}>
Add this to my page
</button>
</div>
)

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { selectBook } from '../actions/index';
import { addToMyPage } from '../actions/index';
import { Link } from 'react-router';
import { selectUser } from '../actions/index.js';
import { getBooks } from '../actions/index';
import _ from 'lodash';

class BookDetails extends Component {
constructor(props) {
super(props);
this.state = {
show: true
};
}
componentWillMount() {
this.props.selectBook(this.props.params.id)
if(this.props.user) {
this.props.selectUser(this.props.user.user.user_id);
}
else {
this.props.selectBook(this.props.params.id);
}
}

renderList() {

const elems = [];
const urlId = parseInt(this.props.params.id);
this.props.list.forEach((list) => {
console.log("list", list.book_id);
console.log("params", this.props.params.id)
if(list.book_id === urlId) {
console.log("true");
elems.push({
book: list.book_id
})
}
})
return elems;
}
render() {
const {post} = this.props;
const {user} = this.props;
const {list} = this.props;
const renderList = this.renderList();
const urlId = parseInt(this.props.params.id);

if(!post) {
return <div>Loading...</div>
}

if(user && list) {
if(urlId === _.get(renderList, '[0].book')) {
return (
<div>
<h1>Title: {post.title}</h1>
<h2>Pages: {post.pages}</h2>
<div>Reviews:</div>
</div>
)
}
else {
return (
<div>
<h1>Title: {post.title}</h1>
<h2>Pages: {post.pages}</h2>
<div>Reviews:</div>
{this.state.show && <button
onClick={() => { this.setState({show:false}, this.props.addToMyPage(
{
userId: user.user.user_id,
bookId: post.book_id
}
))}}>
Add this to my page
</button>
</div>
)
}
}
else {
return (
<div>
<h1>Title: {post.title}</h1>
<h2>Pages: {post.pages}</h2>
<div>Reviews:</div>
</div>
)
}
}
}

function mapStateToProps(state) {
return {
post: state.books.post,
user: state.user.post,
list: state.list.all

}
}
export default connect(mapStateToProps, {selectBook, addToMyPage, getBooks, selectUser})(BookDetails);

最佳答案

您可以根据函数的状态轻松显示按钮:

this.state = {
show: true
};

====

<div>
....
{this.state.show && <button
onClick={() => { this.props.addToMyPage(
{
userId: user.user.user_id,
bookId: post.book_id
}
); this.setState({show:false})}}>
Add this to my page
</button>
}
...
</div>

单击按钮后 - 将状态更改为 show: false 这将导致按钮从 DOM 中删除。

关于javascript - 使用 onClick 时进行 React 渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43288398/

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