[英]How to change className to element after click on another element in React
I have to change(add) className on the first div, after click on "icon-caret-down". 单击“ icon-caret-down”后,我必须在第一个div上更改(添加)className。 My code doesn't work. 我的代码不起作用。 Can you give me some tips? 你能给我一些提示吗?
export default class Nav extends React.Component { render() { var btnClass = classNames({ 'nav-conteiner': true, 'nav-conteiner-mob': this.state.isPressed }); return ( <div classNames={btnClass}> <span className='icon-soundcloud'></span> <h6 id="site-name">SoundCloud</h6> <span className="icon-caret-down" onClick={this.openSerch.bind(this)}></span> <ul> <li><a href='#'>Explore</a></li> <li><a href='#'>Playlist</a></li> </ul> <Search/> </div> ); } openSerch(){ console.log('hello'); this.setState({isPressed:true}); } }
I guess the main error that you didn't announce initial state. 我猜主要的错误是您没有宣布初始状态。
The next thing, that you used wrong attribute "classNames" instead "className" to wrapper. 接下来,您对包装器使用了错误的属性“ classNames”而不是“ className”。
I corrected mistakes, check it out: 我已更正错误,请检查一下:
export default class Nav extends React.Component {
constructor (props) {
super(props);
this.state = {
isPressed: false
}
}
render () {
var btnClass = classNames({
'nav-conteiner': true,
'nav-conteiner-mob': this.state.isPressed
});
return (
<div className={btnClass}>
<span className='icon-soundcloud'></span>
<h6 id="site-name">SoundCloud</h6>
<span className="icon-caret-down" onClick={this.openSerch.bind(this)}></span>
<ul>
<li><a href='#'>Explore</a></li>
<li><a href='#'>Playlist</a></li>
</ul>
<Search/>
</div>
);
}
openSerch () {
this.setState({ isPressed: true });
}
}
export default class Nav extends React.Component { constructor (props) { super(props); this.state = { isPressed: false } } render() { var btnClass = classNames({ 'nav-conteiner': true, 'nav-conteiner-mob': this.state.isPressed }); return ( <div classNames={this.state.isPressed ? btnActiveClass :btnClass }> <span className='icon-soundcloud'></span> <h6 id="site-name">SoundCloud</h6> <span className="icon-caret-down" onClick={this.openSerch.bind(this)}></span> <ul> <li><a href='#'>Explore</a></li> <li><a href='#'>Playlist</a></li> </ul> <Search/> </div> ); } openSerch(){ console.log('hello'); this.setState({isPressed:true}); } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.