React函数写法和组件写法

class写法

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

import "./styles.css";

interface Props {
  message: string;
}
interface State {
  n: number;
}

class App extends React.Component {
  static defaultProps = {
    message: "default message"
  };
  constructor(props) {
    super(props);
    this.state = {
      n: 1
    };
  }
  x = () => {
    this.setState({
      n: 2
    });
  };
  componentDidMount() {}
  render() {
    return 
App
; } } export default App;

函数写法

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import PropTypes from "prop-types";

import "./styles.css";

interface Props {
  message?: any;
}
interface User {
  id: string;
  name: string;
}

const App: React.FunctionComponent = ({
  message = "default message"
}) => {
  const [n, setN] = useState(1);
  const [m, setM] = useState(2);
  const [user, setUser] = useState(null);
  const x = () => {
    setN(n + 1);
  };
  const y = () => {
    setM(m + 1);
  };
  useEffect(() => {
    console.log("mounted");
    return () => {
      console.log("我死了");
    };
  }, []);
  message.split("");
  return (
    

{message}

{n}, {m}
); }; App.defaultProps = { message: "default message" }; App.displayName = "Frank"; App.propTypes = { message: PropTypes.number }; const rootElement = document.getElementById("root"); ReactDOM.render(, rootElement);

你可能感兴趣的:(React函数写法和组件写法)