首页 > 解决方案 > 在 Reactjs 中创建一个可折叠的 ul li

问题描述

react创建可折叠ul/li列表的最佳做法是什么?我希望列表在悬停时展开并在未悬停时关闭。

标签: javascriptcssreactjsfrontend

解决方案


悬停在其上的可折叠手风琴。

jsFiddle 上的工作示例 - https://jsfiddle.net/op088krw/98/

HTML

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

JS

const PRODUCTS = [
  {"id": 1, "name": "Bag of suck", "price": 100, "details": "You don't want to own this!"},
  {"id": 2, "name": "Bag of luck", "price": 200, "details": "You might want to own this!"},
  {"id": 3, "name": "Bag of fuck", "price": 300, "details": "You really want to own this!"}
];



var ItemList = React.createClass({
  getInitialState(){
    return {active: null}
  },
  handleClick(i){
    return (e) => {
      let active = this.state.active === i ? null : i
      this.setState({active: active})
    }
  },
  display(i){
    return this.state.active === i ? 'block' : 'none'
  },
  liClass(i){
    return this.state.active === i ? 'active' : 'inactive'
  },
  Item(props, i) {
    return(
      <li key={i} onMouseEnter={this.handleClick(i)}>
        <span>
          {props.name + '(' + props.price + ')'}
        </span>
        <div style={{display: this.display(i)}}>
          {props.details}
        </div>
      </li>
    )
  },
  render(){
    let {products} = this.props
    return (
     <ul>
      {products.map(this.Item)}
     </ul>
    )
  }
})

const App = React.createClass({
  getInitialState(){
    return {active: null}
  },
  render(){
    return (
    <div>
       <h1> Hover over li items </h1>
       <ItemList products={PRODUCTS} />
    </div>

    )
  }
})

ReactDOM.render(
 <App />,
 document.getElementById("app")
)

推荐阅读