0

我正在发送一个名为标签的数组作为道具,我想在初始状态下分配它,以便显示这些数组元素。使用此代码它们可以正确显示,但我无法编辑它们。当我单击交叉时,它会被删除,但一段时间后它会再次显示。似乎 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
4

1 回答 1

1

问题是,您在本地状态下保存和使用道具,然后修改它们,但是每次组件更新时,您都将状态设置回道具。

// this is where you are setting the state back to 
// props and hence your edit disappears
componentDidUpdate(prevProps, prevState) {
    // debugger;
    if (this.state.tags  !== this.props.tags) {
      this.setState({tags: this.props.tags})
    }
  }

您需要做的不是维护状态中的道具,而是直接修改它,方法是从父级传递一个处理程序来更新道具。

有关如何在父级中传递和更新数据的信息,请参阅此答案

如何在 ReactJS 中将数据从子组件传递到其父组件?

于 2017-11-27T07:54:02.343 回答