React和javascript的入门者,我被困在这个问题上:
当我单击特定的div快门按钮时,如何显示/隐藏特定的div?
这是我的主意,但是如您所见,当我单击“打开”或“关闭”链接时,它会影响每个div。
import React from 'react'
class Qui extends React.Component {
constructor(props) {
super(props);
this.state = { isToggleOn: true };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return(
<div>
<h1>first part</h1>
<a onClick={this.handleClick>
{this.state.isToggleOn ? 'open' : 'close'}
</a>
<div className={this.state.isToggleOn ? 'hidden':'visible'}>
<p> blablabla blablabla </p>
<p> blablabla blablabla </p>
<p> blablabla blablabla </p>
</div>
<h1>second part</h1>
<a onClick={this.handleClick>
{this.state.isToggleOn ? 'open' : 'close'}
</a>
<div className={this.state.isToggleOn ? 'hidden':'visible'}>
<p> onetwothree onetwothree </p>
<p> onetwothree onetwothree </p>
<p> onetwothree onetwothree </p>
</div>
</div>
)
}
}
感谢您的帮助:)。
答案 0 :(得分:1)
您可以在状态中设置activeDivIndex,然后根据activeDivIndex值显示div。
state = {
activeDivIndex: 0
};
handleClick = index => {
this.setState({ activeDivIndex: index });
};
render() {
return (
<div>
<h1>first part</h1>
<a onClick={() => this.handleClick(0)}>
{this.state.activeDivIndex === 0 ? "open" : "close"}
</a>
{this.state.activeDivIndex === 0 && (
<div>
<p> blablabla blablabla </p>
<p> blablabla blablabla </p>
<p> blablabla blablabla </p>
</div>
)}
<h1>second part</h1>
<a onClick={() => this.handleClick(1)}>
{this.state.activeDivIndex === 1 ? "open" : "close"}
</a>
{this.state.activeDivIndex === 1 && (
<div>
<p> onetwothree onetwothree </p>
<p> onetwothree onetwothree </p>
<p> onetwothree onetwothree </p>
</div>
)}
</div>
);
}
您可以在代码和框here中对其进行实时检查。
答案 1 :(得分:0)
您可以为每个div设置一个单独的状态变量,并使用该变量分别显示/隐藏它们。
示例
class Qui extends React.Component {
state = {
showFirstPart: true,
showSecondPart: true
};
toggleFirstPart = () => {
this.setState(prevState => ({
showFirstPart: !prevState.showFirstPart
}));
};
toggleSecondPart = () => {
this.setState(prevState => ({
showSecondPart: !prevState.showSecondPart
}));
};
render() {
const { showFirstPart, showSecondPart } = this.state;
return (
<div>
<h1>first part</h1>
<button onClick={this.toggleFirstPart}>
{showFirstPart ? "Hide" : "Show"}
</button>
{showFirstPart && (
<div>
<p> blablabla blablabla </p>
<p> blablabla blablabla </p>
<p> blablabla blablabla </p>
</div>
)}
<h1>second part</h1>
<button onClick={this.toggleSecondPart}>
{showSecondPart ? "Hide" : "Show"}
</button>
{showSecondPart && (
<div>
<p> onetwothree onetwothree </p>
<p> onetwothree onetwothree </p>
<p> onetwothree onetwothree </p>
</div>
)}
</div>
);
}
}
ReactDOM.render(<Qui />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>