gpt4 book ai didi

javascript - React 中如何判断哪个组件触发了事件处理器?

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

我想将事件处理程序绑定(bind)到 React 中的多个组件。现在我为每个组件设置 className 并使用 event.currentTarget.className 来确定哪个组件触发处理程序。

handleClick: function (e) {
var className = e.currentTarget.className;
if (className === "longComment") {
this.setState({showLongComment: !this.state.showLongComment});
} else {
this.setState({showShortComment: !this.state.showShortComment});
}
},

render: function () {
var topic = this.props.topic;
var shortComment = this.state.showShortComment ? '[-]' : '[+]';
var longComment = this.state.showLongComment ? '[--]' : '[++]';

return (
<li className="topic">
<div className="title">
<a target="_blank" href={api}>
{this.props.children.toString()}
</a>&nbsp;
<span className="longComment" onClick={this.handleClick}>
{longcomment}
</span>
<span className="shortComment" onClick={this.handleClick}>
{shortcomment}
</span>
</div>
{this.state.showLongComment ? <CommentList url={url} /> : null}
{this.state.showShortComment ? <CommentList url={url} /> : null}
</li>
);
}

React 中是否有任何 native 方法来知道哪个组件触发了事件处理程序?

最佳答案

您可以通过将不同的参数绑定(bind)到handleClick 函数来实现您想要的:

handleClick: function (propertyName) {

var newState = {};
newState[propertyName] = !this.state[propertyName];
this.setState(newState);

},

render: function () {
var topic = this.props.topic;
var shortComment = this.state.showShortComment ? '[-]' : '[+]';
var longComment = this.state.showLongComment ? '[--]' : '[++]';

return (
<li className="topic">
<div className="title">
<a target="_blank" href={api}>
{this.props.children.toString()}
</a>&nbsp;
<span className="longComment" onClick={this.handleClick.bind(this,"showLongComment")}>
{longcomment}
</span>
<span className="shortComment" onClick={this.handleClick.bind(this,"showShortComment")}>
{shortcomment}
</span>
</div>
{this.state.showLongComment ? <CommentList url={url} /> : null}
{this.state.showShortComment ? <CommentList url={url} /> : null}
</li>
);
}

关于javascript - React 中如何判断哪个组件触发了事件处理器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28252703/

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