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

如何重构这段React类组件代码?如何学习重构优化代码?

Refactoring Your React Class Component for Better Practice

Hey there! Let's walk through refactoring your component to make it more idiomatic React, maintainable, and aligned with best practices. First, let's break down the rough spots in the original code, then jump into the improved versions.

Key Issues in the Original Code

  • Direct DOM Manipulation: You're using document.querySelector to tweak button text and content visibility. This skips React's state-driven UI model, which can lead to frustrating inconsistencies between your component's state and what's actually rendered in the browser.
  • Redundant Manual Logic: The button text and content visibility are directly tied to the isClicked state, but you're handling them manually instead of letting React render based on state changes.
  • Inline Static Values: Static text like heading3 and p1 are defined inside the render method, meaning they get recreated every time the component renders (not a huge problem here, but it's a bad habit to carry into larger components).

Refactored Class Component Version

Let's fix those issues while keeping it as a class component:

import React from 'react';
import ReactDOM from 'react-dom';

// Move static content outside the component to avoid reinitializing on every render
const HEADING_TEXT = 'this is a heading inside class component';
const PARAGRAPH_TEXT = 'this is a paragraph inside class component';

class ClassComponent extends React.Component {
  state = { isClicked: false };

  handleClicked = () => {
    // Toggle state directly—React will handle updating the UI automatically
    this.setState(prevState => ({ isClicked: !prevState.isClicked }));
  };

  render() {
    const { isClicked } = this.state;

    return (
      <div>
        {/* Button text is determined by state, no DOM hacks needed */}
        <button onClick={this.handleClicked}>
          {isClicked ? 'Show' : 'Hide'}
        </button>
        {/* Control content visibility with conditional rendering (cleaner than manual style changes) */}
        {!isClicked && (
          <div>
            <h1>{HEADING_TEXT}</h1>
            <p>{PARAGRAPH_TEXT}</p>
          </div>
        )}

        {/* Alternative: Use style prop if you want to keep the element in the DOM */}
        {/* <div style={{ display: isClicked ? 'none' : 'block' }}>
          <h1>{HEADING_TEXT}</h1>
          <p>{PARAGRAPH_TEXT}</p>
        </div> */}
      </div>
    );
  }
}

ReactDOM.render(
  <ClassComponent />,
  document.getElementById('root')
);

Even Better: Function Component with Hooks

Since React 16.8, function components with hooks are the go-to approach for most cases. Here's how to convert your component to this modern style:

import React, { useState } from 'react';
import ReactDOM from 'react-dom';

const HEADING_TEXT = 'this is a heading inside class component';
const PARAGRAPH_TEXT = 'this is a paragraph inside class component';

const FunctionComponent = () => {
  const [isClicked, setIsClicked] = useState(false);

  const handleClicked = () => {
    setIsClicked(prev => !prev);
  };

  return (
    <div>
      <button onClick={handleClicked}>
        {isClicked ? 'Show' : 'Hide'}
      </button>
      {!isClicked && (
        <div>
          <h1>{HEADING_TEXT}</h1>
          <p>{PARAGRAPH_TEXT}</p>
        </div>
      )}
    </div>
  );
};

ReactDOM.render(
  <FunctionComponent />,
  document.getElementById('root')
);

What We Improved

  • State-Driven UI: All UI changes are controlled by component state, eliminating direct DOM manipulation. This ensures your state and the rendered DOM are always in sync.
  • Simplified Handler: The click handler now only toggles the state—React takes care of updating the button text and content visibility automatically.
  • Static Content Optimization: Static text is moved outside the component so it's only initialized once, instead of on every render.
  • Cleaner Render Logic: Conditional rendering makes it immediately clear when content should be displayed, and the button text is dynamically set based on state.
  • Modern React Alignment: The hook version is more concise, easier to test, and follows current React best practices.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:50:22