我正在制作一个社交媒体应用程序。我正在循环浏览所有评论并将其显示在 UI 上。当我单击编辑时,输入时总是显示最后一条评论的文本。我尝试了许多不同的东西,改变了结构,使用 bind 来绑定上下文,但没有任何帮助。
我正在使用 React Material UI。
这是代码:
render() {
const { anchorEl } = this.state;
const open = Boolean(anchorEl);
return(
<Panel>
<form noValidate autoComplete="off" onSubmit={this.onSubmit}>
<TextField
id={`comment${this.state.post_id}`}
name="comment"
fullWidth
placeholder="Comment here"
margin="normal"
value={this.state.comment}
onChange={this.handleChange}
InputProps={{
endAdornment : <InputAdornment position="end">
<IconButton onClick={this.resetTextField}>
<CloseIcon/>
</IconButton>
</InputAdornment>
}}
/>
</form>
{this.props.comments && this.props.comments.length > 0 &&
<RenderComments
comments={this.state.comments}
open={open}
anchorEl={this.state.anchorEl}
handleClick={this.handleClick}
handleClose={this.handleClose}
handleDelete={this.handleDelete}
handleEdit={this.handleEdit}
/>
}
</Panel>
)
}
const RenderComments = (props) => {
return props.comments.map(comment =>
<CommentBase
key={comment.id}
comment={comment}
open={props.open}
anchorEl={props.anchorEl}
handleClick={props.handleClick}
handleClose={props.handleClose}
handleDelete={props.handleDelete}
handleEdit={props.handleEdit}
/>
);
};
const CommentBase = ({comment, open, anchorEl, handleClick, handleClose, handleDelete, handleEdit}) => (
<CommentBasePanel>
<CommentText>
{comment.text}
<span style={{ float: 'right', fontSize: 10, color: '#A9A9A9' }}>{moment(comment.created_at).fromNow()}</span>
</CommentText>
<HelperAction>
<MoreVertIcon
id={comment.id}
aria-owns={open ? `simple-popper${comment.id}` : null}
aria-haspopup="true"
variant="contained"
onClick={handleClick}
/>
<Popover
id={`simple-popper${comment.id}`}
open={open}
anchorEl={anchorEl}
onClose={handleClose}
anchorOrigin={{
vertical: 'bottom',
horizontal: 'right',
}}
transformOrigin={{
vertical: 'top',
horizontal: 'right',
}}
>
<Typography style={{ padding: 10, cursor: 'pointer' }} onClick={() => handleEdit(comment)}>
Edit
</Typography>
<Typography style={{ padding: 10, color: red[500], cursor: 'pointer' }} onClick={() => handleDelete(comment.id)}>
Delete
</Typography>
</Popover>
</HelperAction>
</CommentBasePanel>
);
handleEdit = (comment) => {
this.setState({ comment: comment.text, comment_id: comment.id })
};
无论我编辑什么评论,handleEdit 方法中的控制台登录评论总是记录最后一条评论。如您在图像中看到的那样,在第一条评论上编辑会给出最后一条评论文本。