You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何合并两个按钮的事件以简化代码?

Nice catch on the duplicate logic! Keeping your code DRY (Don't Repeat Yourself) is key for maintainability, so let's go through a few straightforward ways to clean up those button handlers:

1. Extract a Reusable Handler Function

This is the most common and recommended approach. Create a single method in your component that handles the shared state update, then accepts the unique vote function as a parameter to execute after:

// Inside your component class
handleVote = (voteAction, post) => {
  // Shared logic first
  this.setState({ disable: true });
  // Then the unique vote action
  voteAction(post);
};

// Updated button JSX
<Button onClick={() => this.handleVote(increasePostsVote, post)}>
  <i className="fa fa-thumbs-o-up fa-lg"/>
</Button>
<Button onClick={() => this.handleVote(decreasePostsVote, post)}>
  <i className="fa fa-thumbs-o-down fa-lg"/>
</Button>

This way, if you ever need to modify the shared logic (like adding a loading state or extra validation), you only have to update one place instead of two.

2. Use a Curried Handler

If you prefer a more functional style, you can create a curried function that first takes the vote action, then returns a function that accepts the post. This can make the JSX a bit cleaner in some cases:

// Curried handler in your component
handleVote = (voteAction) => (post) => {
  this.setState({ disable: true });
  voteAction(post);
};

// Usage in buttons
<Button onClick={() => this.handleVote(increasePostsVote)(post)}>
  <i className="fa fa-thumbs-o-up fa-lg"/>
</Button>
<Button onClick={() => this.handleVote(decreasePostsVote)(post)}>
  <i className="fa fa-thumbs-o-down fa-lg"/>
</Button>

Currying works well if you need to reuse this handler with different vote actions across your component.

3. Inline Shared Logic (Quick Fix)

For a simpler, no-new-method approach, you can define the shared state update as a small inline function and call it in both handlers. This is great for quick refactors without adding extra component methods:

// Inside your render method (or component body)
const setVoteDisabled = () => this.setState({ disable: true });

// Buttons with inline shared logic
<Button onClick={() => {
  setVoteDisabled();
  increasePostsVote(post);
}}>
  <i className="fa fa-thumbs-o-up fa-lg"/>
</Button>
<Button onClick={() => {
  setVoteDisabled();
  decreasePostsVote(post);
}}>
  <i className="fa fa-thumbs-o-down fa-lg"/>
</Button>

All three approaches will eliminate the duplicate setState call, but the first method is the most scalable for future changes. Pick the one that fits your component's structure best!

内容的提问来源于stack exchange,提问作者tulipjie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:03:39