javascript - 渲染中的条件语句

标签 javascript reactjs state render

我正在尝试为我正在处理的网站创建评论部分。提交评论表单(在 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/

相关文章:

javascript - 在 ng-table 上使用 $http GET 加载的 JSON 数据未显示

javascript - 如何将数组用作属性名称?

javascript - 使用 React 的 useCallback hook 代替 useEffect 的目的是什么?

javascript - 在 className if-else 语法中 react JSX

javascript - Magento 2 如何应用 jquery 获取结帐页面中的输入文本值?

JavaScript - 如何将数组与其自身进行交叉比较

javascript - 从右到左 react native - 本地化

angular - 如何在我的 Angular 2 应用程序中保持对话框的状态和进度?

javascript - vuex 注册模块中的未知突变类型

javascript - React JS - 这个函数如何删除 JSON 数据?