【问题标题】:Multiple component with same state name, change one without affection others onclick on parent div?具有相同状态名称的多个组件,在父div上单击时更改一个而不影响其他人?
【发布时间】:2019-02-01 02:30:50
【问题描述】:

所以,我会尽量加快速度,当我单击带有 className“问题”的 div 时,我希望我的图标从上角变为下角,反之亦然(也想让另一个 div 可见/ 无形的)。事情是,我目前正在使用 this.state.icon,所以当我点击一个问题时,所有其他问题的图标也会发生变化(对于 . 这是我的代码:

class FAQ extends React.Component {

constructor() {
    super()
    this.state={
        showMe:true,
        icon:"angle-down"
    }
}

componentDidUpdate(prevProps, prevState, snapshot) {
    console.log(prevState);
}

getReveal(event) {
    this.setState({
        showMe:!this.state.showMe,
        icon: this.state.icon === "angle-up" ? "angle-down" : "angle-up"
    })
}

render() {
    const { menu } = this.props;
    return (
            <div className={styles.container}>
                <div className={styles.category}>
                    <h2>Cat</h2>
                    <div className={styles.question}>
                        <p>Question 1 ?<FontAwesomeIcon className={styles.iconAngle} icon={this.state.icon} /></p>
                    </div>
                    {
                        this.state.showMe?
                    <div className={styles.answer}>
                        <h3 className={styles.titleAnswer}>Title 1</h3>
                        <p>Answer 1 </p>
                    </div>
                    :null
                    }</div>

                    <div className={styles.question} onClick={this.getReveal.bind(this)}>
                        <p>Question 2 ?<FontAwesomeIcon className={styles.iconAngle} icon={this.state.icon} /></p>
                    </div>
                    {
                        this.state.showMe?
                    <div className={styles.answer}>
                        <h3 className={styles.titleAnswer}>title 2</h3>
                        <p>Answer 2 </p>
                    </div>
                    :null
                    }</div>
    );
}

所以,我的问题是,如何更改图标并仅针对我单击的问题显示答案?

提前感谢您的帮助! :)

【问题讨论】:

    标签: javascript html css reactjs


    【解决方案1】:

    您可以通过将问题作为一个单独的组件然后保持它们自己的状态来做到这一点。目前所有问题都由单个状态参数控制,因此切换单个问题的显示/隐藏会影响所有其他问题。如果您将每个问题保留在其自己的组件中并在那里保持显示/隐藏状态,那么您将能够管理每个问题问题的状态独立。希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2019-06-14
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-03
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多