我是React的初学者,我正在尝试通过导航菜单制作侧边栏。当用户单击className为“ frist”的li标记时,组件FrstComponent打开,当用户单击className为“ second”的li标记时,SecondComponent打开,等等。类似于引导选项卡。 这是我的代码
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'));
答案 0 :(得分:3)
我正在尝试为您提供帮助,但是您的代码需要更多重构:)
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);
您需要在渲染时传递 className 来声明和检查此变量。如果您对此代码有疑问,可以提出:)