我正在尝试使用 React.js 中的按钮切换页面上的内容如果我按下按钮,我希望内容消失。如果我再按一次,我希望内容再次出现。我尝试了我能想到的一切,但似乎没有任何效果。我最初尝试了一个三元语句来查看我是否可以切换,但它只是破坏了我的应用程序。有人能告诉我如何改进元素的这一部分吗?这是我所拥有的:
//App.js
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
isToggle: false
};
}
handleClick(e) {
this.setState({ !isToggle ? isToggle: true : isToggle: false });
}
render() {
const style = {
display: none
};
return (
<div>
<h1 className="text-xs-center">List of items:</h1>
<button onClick={this.handleClick.bind(this)} className="btn btn-primary">Toggle</button>
<div className="container" style={!isToggle ? style.display = none : style.display = block}>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</div>
</div>
);
}
}
export default App;
基本上,我想切换元素 1、元素 2、元素 3、元素 4。
最佳答案
如果我要组成组件,这将是它的形状。
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {isToggle: false};
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
this.setState({isToggle: !this.state.isToggle});
}
render() {
return (
<div>
<h1 className="text-xs-center">List of items:</h1>
<button
className="btn btn-primary"
onClick={this.handleClick}
>
Toggle
</button>
<div
style={{display: this.state.isToggle ? 'block': 'none'}}
className="container"
>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</div>
</div>
);
}
}
export default App;
关于javascript - React.js 切换显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43816334/