The premise

Components allow you to break up the UI into separate reusable pieces of code and think about each piece individually.

Component definition

1. The easy way

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
Copy the code

2. Use ES6 classes to define components

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>; }}Copy the code

Components use

Note: Component names must begin with a capital letter.

React will treat components that begin with a lowercase letter as native DOM tags.

Rendering component

  • Dom label
const element = <div />;
Copy the code
  • Custom Components
const element = <Welcome name="Sara" />;
Copy the code
  • Combination of components
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Sara" />
      <Welcome name="Cahal" />
      <Welcome name="Edite" />
    </div>
  );
}

ReactDOM.render(
  <App />.document.getElementById('root'));Copy the code

Read-only of Props

A component must never modify its props, either using a function declaration or through a class declaration. Consider the sum function:

function sum(a, b) {
  return a + b;
}
Copy the code

Such a function is called a “pure function” because it does not attempt to change the input parameter, and the same input parameter returns the same result multiple times.

React is very flexible, but it also has a strict rule:

All React components must protect their props from being changed like pure functions.