我正在发送一个名为标签的数组作为道具,我想在初始状态下分配它,以便显示这些数组元素。使用此代码它们可以正确显示,但我无法编辑它们。当我单击交叉时,它会被删除,但一段时间后它会再次显示。似乎 handelClose 方法中的 setState 不起作用。
import React from 'react';
import ReactDOM from 'react-dom';
import { Tag, Input, Tooltip, Button } from 'antd';
class EditableTagGroup extends React.Component {
constructor(props) {
super(props);
this.state = {
tags: [],
inputVisible: false,
inputValue: '',
};
}
handleClose = (removedTag) => {
// debugger;
const tags = this.state.tags.filter(tag => tag !== removedTag);
console.log(tags);
// debugger;
this.setState({ tags: tags });
}
showInput = () => {
this.setState({ inputVisible: true }, () => this.input.focus());
}
handleInputChange = (e) => {
this.setState({ inputValue: e.target.value });
}
handleInputConfirm = () => {
const state = this.state;
const inputValue = state.inputValue;
let tags = state.tags;
if (inputValue && tags.indexOf(inputValue) === -1) {
tags = [...tags, inputValue];
}
console.log(tags);
this.setState({
tags,
inputVisible: false,
inputValue: '',
});
this.props.onSelect(tags);
}
// componentDidUpdate(prevProps, prevState) {
// this.setState({tags: this.props.tags})
// }
componentDidUpdate(prevProps, prevState) {
// debugger;
if (this.state.tags !== this.props.tags) {
this.setState({tags: this.props.tags})
}
}
saveInputRef = input => this.input = input
render() {
const {tags , inputVisible, inputValue } = this.state;
return (
<div>
{tags.map((tag, index) => {
const isLongTag = tag.length > 20;
const tagElem = (
<Tag key={tag} closable={index !== -1} afterClose={() => this.handleClose(tag)}>
{isLongTag ? `${tag.slice(0, 20)}...` : tag}
</Tag>
);
return isLongTag ? <Tooltip title={tag} key={tag}>{tagElem}</Tooltip> : tagElem;
})}
{inputVisible && (
<Input
ref={this.saveInputRef}
type="text"
size="small"
style={{ width: 78 }}
value={inputValue}
onChange={this.handleInputChange}
onBlur={this.handleInputConfirm}
onPressEnter={this.handleInputConfirm}
/>
)}
{!inputVisible && <Button size="small" type="dashed" onClick={this.showInput}>+ New Tag</Button>}
</div>
);
}
}
export default EditableTagGroup