如何确定哪个组件触发了 React 中的事件处理程序?

IT技术 javascript reactjs
2021-05-06 11:38:37

我想将一个事件处理程序绑定到 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 中是否有任何本地方式可以知道哪个组件触发了事件处理程序?

1个回答

您可以通过将不同的参数绑定到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>
    );
}