React notes components-the use of props and state (2)

How to use props in components

https://codesandbox.io/s/dawn-shape-bofqp?file=/src/index.js:488-492, first of all, here is the link to the complete code, you can refer to it.

index.js

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

import "./styles.css";

function App() {
  return (
    <div className="App">
      父节点
      <Son />
    </div>
  );
}

class Son extends React.Component {
  constructor() {
    super();
    this.state = {
      n: 0
    };
  }
  add() {
    this.setState({ n: this.state.n + 1 });
  }
  render() {
    return (
      <div className="Son">
        子节点 n: {this.state.n}
        <button
          onClick={() => {
            this.add();
          }}
        >
          +1
        </button>
        <Grandson />
      </div>
    );
  }
}

const Grandson = () => {
  const [n, setN] = React.useState(0);
  return (
    <div className="Grandson">
      孙子 n:{n}
      <button onClick={() => setN(n + 1)}>+1</button>
    </div>
  );
};

const rootElement = document.querySelector("#root");
ReactDOM.render(<App />, rootElement);

There are three components App, Son, and Grandson in the above source code. First, let's change the code of the three components and pass a value between them.

function App() {
  return (
    <div className="App">
      父节点
      <Son messageForSon="子节点你好" />
    </div>
  );
}

class Son extends React.Component {
  constructor() {
    super();
    this.state = {
      n: 0
    };
  }
  add() {
    this.setState({ n: this.state.n + 1 });
  }
  render() {
    return (
      <div className="Son">
        子节点 n: {this.state.n}
        <button
          onClick={() => {
            this.add();
          }}
        >
          +1
        </button>
        &nbsp;&nbsp;&nbsp;父节点给我的消息:{this.props.messageForSon}
        <Grandson messageForGrandson="孙节点你好" />
      </div>
    );
  }
}

const Grandson = (props) => {
  const [n, setN] = React.useState(0);
  return (
    <div className="Grandson">
      孙子 n:{n}
      <button onClick={() => setN(n + 1)}>+1</button>
      &nbsp;&nbsp;&nbsp;子节点给我的消息:{props.messageForGrandson}
    </div>
  );
};

You can see that we used <Son messageForSon="子节点你好" />this writing method to pass a messageForSon property to the Son component in the App component ,

In the Son class component, by {this.props.messageForSon}obtaining the attribute value passed by the parent component,

In the Son component, <Grandson messageForGrandson="孙节点你好" />a messageForGrandson property is passed to the Grandson component,

In the function component of Grandson, {props.messageForGrandson}the property value passed by the parent component is obtained.

to sum up

Function components use props.property names to obtain external transfer properties

Class components use this.props. property command to obtain external transfer properties

Guess you like

Origin blog.csdn.net/cainiao1412/article/details/108375089
Recommended