简体   繁体   English

我在反应中映射项目,每个项目下面都有一个文本用于评论,当我在一个框中输入时,文本出现在所有框中

[英]I am mapping items in react, each item has a text are underneath for a comment, when I type in one box the text appears in all the boxes

I am mapping items in react, each item has a text area underneath for a comment, when I type in one box the text appears in all the boxes.我在反应中映射项目,每个项目下面都有一个用于评论的文本区域,当我在一个框中键入时,文本出现在所有框中。 I know it's because the values are the same this.state.comment but I not sure how to fix it.我知道这是因为值相同 this.state.comment 但我不知道如何解决它。 I have tried changing the value but i haven't figured out a way that would work since the the number of item can be 1 or 1000 depending on how many items are added.我尝试过更改值,但我还没有找到可行的方法,因为项目的数量可以是 1 或 1000,具体取决于添加的项目数量。

  class Content extends React.Component {
  state = {
   
    allUserItems: [],
    image: null,
    url: "",
    video: "",
    isActive: false,
    isActive2: false,
    comment: "",
    checkInputID: null,
    whichComment: null,
    optionId: "",
    edit_id: "",
    editContent: "",
    editPicture: "",
    comment_id: "",
    comOption_id: "",
    postComment_id: "",
    editComment: "",
    isNotiOpen:false,

    componentDidMount() {
    console.log(this.props)



    this.listFriendsItems()

}



   listFriendsItems = () => {

    API.getFriendsItems({ friends: this.props.userInfo.friends, })

        .then(res => {

            this.setState({ allUserItems: res.data })
            console.log(res.data)


        })

        .catch(err => console.log(err));

   }








   handleChange = e => {


    this.setState({
        [e.target.name]: e.target.value
    });
    };



  submitComment = (id,posters_id) => {
    API.saveComment(id, {

        comment: this.state.comment,
        user_id: this.props.userInfo.user_ID,
        user: this.props.userInfo.firstname + " " + 
    this.props.userInfo.lastname,
        picUrl: this.state.url,
       })
        .then(res => console.log(res))
        .catch(err => console.log(err));

        let data ={
        comment: this.state.comment,
        user_id: this.props.userInfo.user_ID,
        name: this.props.userInfo.firstname + " " + 
      this.props.userInfo.lastname,
        userPic: this.state.url,

        }
        if(this.props.userInfo.user_ID !== posters_id){

        this.props.saveNotification(posters_id,data,id)
        }

    
    this.setState({ comment: "", checkInputID: null }, () => 
   this.listFriendItems());
    }



    <section className="feed ">

                         {this.state.allUserItems.length ? (

                        <div>
                            {this.state.allUserItems.map(content => {

                                return (



                <div className="feed_Container" key={content._id} >
                                    <div className="info">
                                       
                                    <div className="uploadedInfo">
                                        {(content.picUrl === "" ) ? <div 
     className="story"> </div> :
                                            <div className="miniUpImage"><img 
      className={`${(content.picUrl === "") ? "story" : "miniUpImage"}`} src= 
     {content.picUrl} alt="uploaded pic" /></div>
                                        }

                                        <div className={(content.videoUrl === 
   "") ? "noVideo" : "uploadedVideo"}> <VideoPost video={content.videoUrl} /> 
  </div>
                                    </div>
                                    <div className="colorBackground">
                                        <div className="updateInfo">
                                            <div className="timenOptions"> 
  <div className="time">{moment(content.dateCreated).calendar()}</div>
                                                <div className= 
{(this.state.optionId === content._id) ? "optionsContainer active" : 
 "optionsContainer"} onClick={() => this.optionsClicked(content._id)} >

                                                    <div className= 
{(content.user_ID === this.props.userInfo.user_ID) ? "options" : 
  "noOptions"}> ...</div>
                                                    <div 
 className="optionsDropdown">
                                                        <ul 
 className="optionsList">
                                                            <div 
 className="edit" onClick={() => this.editPostClicked(content._id, 
 content.content, content.picUrl)}> Edit</div>
                                                            <div 
 className="delete" onClick={() => this.removePost(content._id)}>Delete</div>


                                                        </ul>
                                                    </div>
                                                </div>

                                            </div>
                                            <p>{content.content}
                                            </p>

                                        </div>
                                       
                                            
                                        </div>

    <div className="mapComments">{content.comments.map((comment, picUrl) =>
     <div key={picUrl} className="commentList"><div className="timeStamp"> 
      {moment(comment.dateCreated).calendar()}<div>
     <div className={(this.state.comOption_id === 
     comment._id"comOptionsContainer active" : "comOptionsContainer"} 
     onClick={() => this.commentOptions(comment._id)} >
    <button type="button" className={(comment.user_id === 
    this.props.userInfo.user_ID) ? "commentOptions" : "noOptions"} ><i 
     class="far fa-comment-dots"></i></button>

    <div className="comOptionsDropdown">
    <ul className="optionsList">
    <div className="edit" onClick={() => 
    this.editCommentClicked(content._id, 
    comment._id, content.content, comment.comment, content.picUrl)}> 
    Edit</div>
    <div className="delete" onClick={() => this.removeComment(content._id, 
   comment._id)}>Delete</div>


  </ul>
   </div>
  </div>

 </div> </div><span> &nbsp; <strong>{comment.user} </strong>  &nbsp; 
 </span>   
{comment.comment}
                                                    <div className= 
{(comment.picUrl !== "") ? "commentPic" : "nocommentPic"}><img 
 className="commentUrl" src={comment.picUrl} alt="comment pic" /></div> 
 </div>
                                                 )}
 <div className="responseComments">
  <textarea name="comment" value={this.state.comment} onChange= 
  {this.handleChange} className="commentArea" placeholder="Comment" 
  rows="8" 
   cols="80" />

 <div className="commentPhoto">
 <button type="button" className="button photo" onClick={() => { 
 this.fileInput2.click(); this.getID(content._id); }}> <i className="far 
  fa-images"></i></button>


   </div>

  </div>
 <div>

 <input type="file" style={{ display: "none" }} onChange= 
 {this.handleImageSelected2} ref={fileInput => this.fileInput2 = fileInput} 
 />
                                                <img className= 
{(this.state.checkInputID === content._id) ? "uploadReady active" : 
"uploadReady"} src={this.state.url} alt="preview" height="40" width="50" />

 <progress className= {(this.state.checkInputID === content._id) ? 
 "uploadReady 
 active" : "uploadReady"} value={this.state.progress} max="100" />
 <button className= {(this.state.checkInputID === content._id) ? 
"uploadReady 
 active" : "uploadReady"} onClick={this.handleUpload}>Upload</button>  
<span 
className={(this.state.checkInputID === content._id) ? "uploadReady active" 
: 
"uploadReady"}>File </span>
</div>

<div className="commentButtons">
<div className="replyButton" onClick={this.state.comment === "" && 
this.state.url === "" ? null : () => 
this.submitComment(content._id,content.user_ID)} ><i className="fas fa- 
share"> 

<div className="likessection">
                                                   
{(content.likes.findIndex(i => i.user_id === this.props.userInfo.user_ID) > 
-1) ?
<div className="likeButton" onClick={() => 
this.removeLikes(content._id)}>Unlike</div>
: <div className="likeButton" onClick={() => 
 this.handleLikes(content._id)}> 
<i 
className="far fa-thumbs-up"></i></div>}
 </div>


      </div>

        </div>




       </div>

             </div>

            );
              })
          }
       </div>

You have to initialize state comments with the number of comments you have.您必须使用您拥有的评论数来初始化 state 评论。 In your constructor create your comments like this, an array of comments:在您的构造函数中创建您的评论,如下所示,一组评论:

this.state= {
comments: new Array(n) //n is your number of comments
}

In the handleChange function, you will have to pass the index of comment to be updated.在 handleChange function 中,您必须传递要更新的评论索引。

handleChange = (commentIndex, e) => {
  const commentsUpdated = this.state.comments.map((comment, i) => {
    if (i == commentIndex) return e.target.value;
    else return comment;
  });
  this.setState({ comments: commentsUpdated });
};

And you have to update the JSX, you will need to render a collection of comments, and every comment connect with its comment state.而且您必须更新 JSX,您将需要渲染一组评论,并且每个评论都与其评论 state 连接。

<div className="responseComments">
  {this.state.comments.map((comment, i) => (
    <textarea
      name="comment"
      value={comment}
      onChange={e => this.handleChange(i, e)}
      className="commentArea"
      placeholder="Comment"
      rows="8"
      cols="80"
    />
  ))}
</div>;
 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我输入一个文本框时,会填满一些文本框 - I have a few text boxes that fill when I type in one 当我使用select2 jquery选择&#39;ALL&#39;项目时,如何禁用选择框中的所有项目 - How to disable all items in select box when i am selecting 'ALL' item using select2 jquery 当我们在文本框中键入 pincode 时,如何编写反应代码以显示 pincode 中的所有位置? - How to i write a react code to display all the locality in a pincode when we type pincode in text box? 我有2个文本框和一个按钮! 当我单击按钮时,它应该在所选文本框中写1,但是我的代码不起作用 - I have 2 text Boxes and one button! When I click on button it should write 1 in the chosen text box but my code is not working 填充一个文本框后如何动态添加文本框? - How to add text boxes dynamically when one text box is filled? 我想在jQuery厚框中显示带有文本的加载图像 - I want to show an loading image with text underneath in a jquery thick box 在组合框中选择项目时如何显示隐藏的文本框 - How to show hidden text boxes when items are selected in a combo box 我无法在输入类型的文本框中输入数值 - I am not able to enter numeric value in text box of type input jQuery的所有所有文本框 - jquery each for all text boxes 加载页面时会出现一个文本框,即使我已将其“样式:显示”设置为无 - A text box appears when I load the page even though I have set its “style:display” to none
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM