反应显示/隐藏内容

时间:2019-05-22 12:26:17

标签: reactjs

我正在尝试使用React创建一个切换内容按钮。但是我只能使其打开,而再次单击时则无法关闭。有人可以看看一下,让我知道要在代码中进行更改以完成此操作吗?

这是我到目前为止所拥有的:

class Test extends React.Component {
  constructor(props) {
        super(props)

        this.state = {
            activeLocation: 0,
        }
    }

  changeActiveLocation = (activeLocation) => {
        this.setState({
            activeLocation: activeLocation,
        });
    }

  render() {
    const activeLocation = company.locations[this.state.activeLocation];

    return (
      {company.locations.map((location, index) => (
      <div className="test-item">
        <div className="test-item-container" onClick={() => {this.changeActiveLocation(index)}}>
          <div className="test-item-header">
            <h3>Text goes here!</h3>
            <a><FontAwesomeIcon icon={(this.state.activeLocation === index) ? 'times' : 'chevron-right'} /></a>
          </div>
        </div>
      </div>
    ))}
    )
  }
}

谢谢!

1 个答案:

答案 0 :(得分:3)

您正在将活动位置设置为与您已经单击的位置相同的位置,因此this.state.activeLocation === index始终为true。我将使用isOpen状态值将位置重构为它们自己的组件,该状态值在单击位置时会更新。因此,如下所示:

// test class
class Test extends React.Component {
  constructor(props) {
        super(props)

        this.state = {
            activeLocation: 0,
        }
    }

  changeActiveLocation = (activeLocation) => {
        this.setState({
            activeLocation: activeLocation,
        });
    }

  render() {
    const activeLocation = company.locations[this.state.activeLocation];

    return (
      {company.locations.map((location, index) => (
          <LocationItem location={location} onClick={() => this.changeActiveLocation(index)} />
      ))}
    )
  }
}

// LocationItem
class LocationItem extends React.Component {
    state = { isOpen: false };

    handleClick = () => {
     this.setState(prevState => { isOpen: !prevState.isOpen});
     // call parent click to set new active location if that's still needed
     if(this.props.onClick) this.props.onClick;
    }

    render() {
        return <div className="test-item">
        <div className="test-item-container" onClick={this.handleClick}>
          <div className="test-item-header">
            <h3>Text goes here!</h3>
            <a><FontAwesomeIcon icon={(this.state.isOpen ? 'times' : 'chevron-right'} /></a>
          </div>
        </div>
      </div>
    }
}