react class 写法和react 函数写法的区别

react qmt 43℃
// 传统写法
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      color: "blue",
    };
  }

  onSwitchColor = () => {
    const { color } = this.state;
    this.setState({
      color: color === "blue" ? "red" : "blue",
    });
  };

  render() {
    const { color } = this.state;
    return (
      <div>
        <div style={{ color: color }}>I like color: {color}</div>
        <button onClick={this.onSwitchColor}>Click me</button>
      </div>
    );
  }
}

// hooks 写法
function App2() {
  const [color, setColor] = useState("blue");
  const onSwitchColor = () => {
    setColor(color === "blue" ? "red" : "blue");
  };

  return (
    <div>
      <div style={{ color: color }}>I like color: {color}</div>
      <button onClick={onSwitchColor}>Click me</button>
    </div>
  );
}

然后index.js 文件如下:

import React from "react";
import ReactDOM from "react-dom/client";

import App from "./App"; //这里替换不同的app名字

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);

效果如下:

转载请注明:QMT|Ptrade量化交易 » react class 写法和react 函数写法的区别

喜欢 (0)