想知道是否有方法可以在没有构造函数的情况下渲染组件。
下面是我的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>
)
d
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);
答案 0 :(得分:1)
您可以根据功能状态轻松显示按钮:
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中删除。