我需要一些关于React中的类组件的帮助。
映射数组"list"后,我正在字符串中更改li的类。你能告诉我在这种情况下我该如何使用这种状态吗。当我点击
我可以在不映射列表的情况下做到这一点,因为我不想为每个Composant重复代码。
非常感谢你的帮助,我希望能理解我
const list = ['Biographie', 'CV', 'Blog'];
class Navbar extends Component {
state = {
Biographie: true,
CV: false,
Blog: false,
};
show = (e) => {
list.map(item=> this.setState ({ [item]: false}))
this.setState({ [e.target.id]: true });
};
render() {
return (
<div className="navbar">
<ul className="list">
{list.map((item) => (
<li
onClick={this.show}
id={item}
className={this.state ? 'active' : ''} // How can I change class when state = true ?
>
{' '}
{item}
</li>
))}
</ul>
<Biographie info={this.state.Biographie} />
<CV info={this.state.CV} />
<Blog info={this.state.Blog} />
</div>
);
}
}
是否有必要将状态设置为Object?如果不是,那么简化,让状态仅作为字符串。。。
state = null
const show = (e) => { this.setState(e.target.id) }
className={this.state === item ? 'active' : ''}
使用括号表示法访问您所在州的属性。
{list.map((item) => (
<li
onClick={this.show}
id={item}
className={this.state[item] ? 'active' : ''}
>
{' '}
{item}
</li>
))}
由于您在show
内设置id的状态,
你可以做
className={this.state[item] ? 'active' : ''}
如果你打算只使用一个有源元件,我建议你使用这样的东西来代替
state = {
active:"Biographie"
};
和
{list.map((item) => (
<li
onClick={()=>setState({active:"item"})}
id={item}
className={this.state.active === item ? 'active' : ''}
>
{item}
</li>
))}
感谢大家的回答。最好知道:(
多亏了你,我成功地展示了这个组件,但可能有更好的方法。我再次重复一遍,我不喜欢它:(。
我下面的代码:
{this.state.active === 'Biographie' &&
<Biographie />}
{this.state.active === 'CV' &&
<CV info={this.state.active} />}
{this.state.active === 'Blog' &&
<Blog info={this.state.active} /> }