Show/Hide Component in React

问题: I am a beginner in the React and I am trying to make a sidebar with a navigation menu. When user click on the li tag with className "frist", the component FrstComponent ope...

问题:

I am a beginner in the React and I am trying to make a sidebar with a navigation menu. When user click on the li tag with className "frist", the component FrstComponent opens, when user click on the li tag with className "second" SecondComponent opens etc. Like bootstrap tabs. This is my code

    class Navigation extends React.Component {
 constructor(props) {
    super(props)
    this.state = {
       isActive: "first"
    }
    this.handleClickChange =this.handleClickChange.bind(this)
  }

  handleClickChange(){
    this.setState={
        isActive: !this.state.isActive
    }
  }

  render() {
    const {active} = this.state.isActive
    if(active === 'first'){
      return <FristComponent/>
    }
    if(active === 'second'){
      return <SecondComponent/>
    }
    return (
      <div>
      <ul>
        <li 
        className="first"
        onClick={this.handleClickChange} 
        >
          FIRST

        </li>
        <li 
          className="second"   
          onClick={this.handleClickChange}
          >
          SECOND
        </li>
        <li className="third">THIRD</li>
        <li className="fourth">FOURTH</li>
        <li className="fifth">FIFTH</li>
      </ul>

      </div>
    )
  }
}

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

回答1:

i'm trying to help you, but your code need more refactoring :)

import React from "react"
import ReactDOM from "react-dom";

class Navigation extends React.Component {
  state = {
    active: "first"
  }

  handleClickChange = e => {
    const { className } = e.target

    this.setState({ active: className})
  }

  render() {
    const { active } = this.state

    return (
      <div>
        {active === 'first' && <div>First Component</div>}

        {active === 'second' && <div>Second Component</div>}

        <ul>
          <li className="first"
            onClick={this.handleClickChange}
          >
            FIRST

        </li>
          <li
            className="second"
            onClick={this.handleClickChange}
          >
            SECOND
        </li>
          <li className="third">THIRD</li>
          <li className="fourth">FOURTH</li>
          <li className="fifth">FIFTH</li>
        </ul>

      </div>
    )
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Navigation />, rootElement);

You need to pass on className to state and check this variable when you rendering. If you have a questions by this code, you can ask :)

  • 发表于 2019-03-06 23:17
  • 阅读 ( 261 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除