【问题标题】:Hide list items except the one you click on in React隐藏列表项,您在 React 中单击的项除外
【发布时间】:2016-12-11 16:23:46
【问题描述】:

我有一个 HTML 列表作为 React 组件,其中所有列表项都是从我循环的一些数据创建的。

这就是我想在 React 中实现的目标。

  1. 单击列表项之一
  2. 隐藏除我单击的项目之外的所有其他列表项目
  3. 单击显示的列表项
  4. 现在应该显示所有列表项

有什么想法吗?

谢谢

伊恩

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

试试这个:

<div id="app"></app>

然后:

class Application extends React.Component {
  constructor(props){
    super(props);

    this.state = {
      one: "",
      two: "",
      three: "",
      four: "",
      clicked: false
    }
  }

  handleClick(name, event){
    event.preventDefault();
    if(this.state.clicked){
      this.setState({one: "",two: "", three: "", four: "", clicked: false})
    }else{
      switch(name){
        case "One":
          this.setState({two: "hide", three: "hide", four: "hide", clicked: true});
          break;
          case "Two":
          this.setState({one: "hide", three: "hide", four: "hide", clicked: true});
          break;
          case "Three":
          this.setState({two: "hide", one: "hide", four: "hide", clicked: true});
          break;
          default:
          this.setState({two: "hide", three: "hide", one: "hide", clicked: true});
      }
    }
  }

  render() {
    return <div>
      <ul>
        <a href="" className={this.state.one} onClick={this.handleClick.bind(this, "One")}><li >One</li></a>
        <a href="" className={this.state.two} onClick={this.handleClick.bind(this, "Two")}><li>Two</li></a>
        <a href="" className={this.state.three} onClick={this.handleClick.bind(this, "Three")}><li>Three</li></a>
        <a href="" className={this.state.four} onClick={this.handleClick.bind(this, "Four")}><li>Four</li></a>
      </ul>
    </div>;
  }
}


React.render(<Application />, document.getElementById('app'));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 2013-04-23
    相关资源
    最近更新 更多