Reactjs在“切换”按钮上隐藏和取消隐藏所有记录

时间:2019-01-21 20:28:54

标签: reactjs

Reactjs 隐藏和取消隐藏“切换”按钮上的所有记录单击

我在数组中有3条记录。单击“切换”按钮时,我需要分别隐藏和取消隐藏每个记录。

我的问题是,每次单击特定的切换按钮时,它不会隐藏并取消隐藏该记录,而是会 隐藏和取消隐藏所有三个记录。

我想我需要为每个切换按钮设置一个defmacro print_block(_msg, do: code_block) do IO.inspect(code_block) code_block end 。有人可以帮我吗

{post.id}

1 个答案:

答案 0 :(得分:0)

一种方法是,向数据中的每个项目添加一个标志,然后切换该标志:

class AutoButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      shown: true,
    };
  }

  componentDidMount() {
    this.setState({
      data: [
        { id: "1", title: "my first title", visible: true },
        { id: "2", title: "my second title", visible: true },
        { id: "3", title: "my third title", visible: true }
      ]
    });
  }


  toggle(id) {
    const newData = this.state.data.map(item => {
      if(item.id === id) {
        return { ...item, visible: !item.visible};
      }

      return item;
    })

    this.setState({
      data: newData
    });
  }


  render() {
    return (
      <div>
        <label>
          <ul>
            {this.state.data.map((post, i) => (
              <li key={i}>
                <h2 style={{ display: post.visible ? "block" : "none"}}> {post.title} --{post.id} </h2>
                <button onClick={this.toggle.bind(this, post.id)}>Toggle</button>
                <br />
              </li>
            ))}
          </ul>
        </label>
      </div>
    );
  }
}

编辑

另一种方法是跟踪隐藏的项目,例如:

class AutoButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      shown: true,
      hiddenItems: []
    };
  }

  componentDidMount() {
    this.setState({
      data: [
        { id: "1", title: "my first title" },
        { id: "2", title: "my second title" },
        { id: "3", title: "my third title" }
      ]
    });
  }


  toggle(id) {

    if(this.isHidden(id)) {
      const newHiddenItems = this.state.hiddenItems.filter(item => item !== id);
      this.setState({
        hiddenItems: newHiddenItems
       });
    } else {
      this.setState((state) => ({
        hiddenItems: state.hiddenItems.concat(id)
      }));
    }
  }

  isHidden(id) {
    return this.state.hiddenItems.includes(id);
  }

  render() {
    return (
      <div>
        <label>
          <ul>
            {this.state.data.map((post, i) => (
              <li key={i}>
                <h2 style={{ display: this.isHidden(post.id) ? "none" : "block"}}> {post.title} --{post.id} </h2>
                <button onClick={this.toggle.bind(this, post.id)}>Toggle</button>
                <br />
              </li>
            ))}
          </ul>
        </label>
      </div>
    );
  }
}