gpt4 book ai didi

javascript - 使用 react 切换箭头

转载 作者:行者123 更新时间:2023-11-30 08:27:00 24 4
gpt4 key购买 nike

我正在尝试使用 React 切换箭头。网上找了一些例子,还是不行。

这是我目前所拥有的:

class Footer extends React.Component {

constructor(props) {
super(props);
this.state = {
active: false,
};
}

handleClick() {
const currentState = this.state.active;
this.setState({
active: !currentState
})
}


render() {
return (
<footer className="footer">
<section className="container">
<a className="visible-xs" role="button">
Social
<i onClick={this.handleClick} className={this.state.active ? "fa fa-chevron-up" : "fa fa-chevron-down"} aria-hidden="true"></i>
</a>
</section>
</footer>
)
}
}

module.exports = Footer;
  

如有任何帮助,我们将不胜感激。

最佳答案

问题是您的 handleClick 函数未在预期范围内被调用。

来自React doc :

You have to be careful about the meaning of this in JSX callbacks. In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.

在构造函数的末尾添加这行代码:

// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);

关于javascript - 使用 react 切换箭头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44054691/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com