我想将事件处理程序绑定到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>
<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中有什么本机方法可以知道哪个组件触发了事件处理程序?
最佳答案
您可以通过将不同的参数绑定到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>
<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/