javascript - 渲染中的条件语句
问题描述
我正在尝试为我正在处理的网站创建评论部分。提交评论表单(内部AfterCommentButtonClick
)后,状态formSubmitted
更改false
为true
触发渲染方法内的条件语句。这会调用一个子组件,该组件接收用户评论并对其进行一些样式设置。我遇到的问题是,我希望我的应用程序允许多个评论。有没有办法保存以前呈现的评论,然后创建一个新的实例,<UserComment>
就像当前一样,在表单提交之后,旧的被简单地覆盖。我还需要textInput
在提交表单后重置状态,以便为下一条评论重置表单。但是,我再次不确定如何在不输入的情况下执行此操作setState
内部渲染,这将导致无限循环
import React from 'react'
import UserComment from './UserComment'
class CommentSection extends React.Component {
constructor(props){
super(props)
this.state = {selectedFile: this.props.selectedFile, textinput : '', formSubmitted:false}
}
onFormSubmit (event){
event.preventDefault()
this.setState({formSubmitted:true})
}
render(){
//conditional render depending on if comment button has been clicked or not. props.selectedFile only
//passed here from parent if user clicks comment button
const file = this.props.selectedFile
let messageToUser
if (file !=null){
messageToUser = <AfterCommentButtonClick
selectedFile = {file}
onTextChange = {(e)=> this.setState({textinput: e.target.value})}
onFormSubmit = {(e)=>this.onFormSubmit(e)}
/>
}else {
messageToUser = <BeforeCommentButtonClick />
}
return (
<div>
<div> {messageToUser}</div>
<div className="ui container comments">
{this.state.formSubmitted &&
<UserComment commentText = {this.state.textinput}/>
/*conditionally send text typed into comment bar if user submits form*/
}
</div>
</div>
)
}
}
解决方案
您可以添加另一个状态字段以将评论存储在数组中。因此,当您收到新评论时,请执行以下操作:
this.setState({
comments: [...this.state.comments, newComment]
});
在您的渲染方法中,您映射到该数组并为 this.state.comments 中的每个评论显示一个评论组件
this.state.comments.map(comment => <UserComment commentText = {comment}}/>);