gpt4 book ai didi

javascript - 渲染中的条件语句

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

我正在尝试为我正在处理的网站创建评论部分。提交评论表单(在 AfterCommentButtonClick 内)后,状态 formSubmittedfalse 更改至 true这会触发 render 方法中的条件语句。这将调用一个子组件,该组件接收用户评论并对其进行一些样式设置。我遇到的问题是,我希望我的应用程序允许多个评论。有没有办法保存之前渲染的评论,然后创建<UserComment>的新实例?与目前一样,在提交表单之后,旧的被简单地覆盖了。我还需要重置 textInput提交表单后的状态,为下一条评论重置表单。但是,如果不输入setState,我又不确定如何做到这一点。在 render 内部,这将导致无限循环

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>
)
}

}

最佳答案

创建一个功能组件来呈现您提交的所有评论。为此,您需要保持“已提交评论”数组处于状态,并且在提交新评论时,只需将新用户评论添加到已提交评论数组中。将提交的评论数组从状态传递到您的新功能组件。使用 array.map()函数通过渲染 <UserComment/> 来渲染提交的组件数组对于数组中的每一项。

因此,在提交用户评论时,它只会添加到提交的评论组件中,UI 会重新呈现并更新您提交的评论中的新 UserComment。这应该是完全独立的逻辑。

<CommentsSection/> 的渲染方法组件看起来像这样:

render() {
return (<div>
{this.props.submittedComments.map((comment) => (
<UserComment author={comment.author} content={comment.content}></UserComment>))}
</div>);
}

关于javascript - 渲染中的条件语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57309988/

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