[React log] Function components and class components

1. There are two requirements for defining components:

  • The component name must start with an uppercase letter
  • The return value of the component can only have one root element

2. Function components

function Welcome (props) {
    
    
  return <h1>Welcome {
    
    props.name}</h1>
}
ReactDOM.render(<Welcome name='react' />, document.getElementById('root'));
  • The data component receives a single props object and returns a React element
  • The operation is very simple
  • The functions that can be implemented are very simple, just simply call and return to JSX

3. Class components

class Welcome extends React.Component {
    
    
  render() {
    
    
    return (
      <h1>Welcome {
    
     this.props.name }</h1>
    );
  }
}
ReactDOM.render(<Welcome name='react' />, document.getElementById('root'));
  • Whether using a function or class to declare a component, it must never modify its own props.
  • All React components must be pure functions and it is forbidden to modify their own props.
  • React is a single-item data flow. If the parent component changes the attribute, the child component view will be updated.
  • The property props is passed from outside, the state state is the component itself, and the state can be modified in the component at will
  • The operation is relatively complicated, and some more complex business scenarios can be realized.
  • Functional components can be understood as static components (the content in the component is fixed when it is called, and it is difficult to modify), and in this way, the content can be dynamically updated and rendered according to the internal state of the component

4. Difference

Of course, there is a difference between a function component and a class component, and the performance of a function component is higher than that of a class component, because the class component needs to be instantiated when used, and the function component can directly execute the function to get the return result. In order to improve performance, try to use functional components.

the difference Function component Class component
Is there this No Have
Is there a life cycle No Have
Whether there is state No Have

Guess you like

Origin blog.csdn.net/u013034585/article/details/106147750