Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

React technology 2021 React Technology 2021 React Technology (Used to read articles and documents, now feel a little uncomfortable to brush the video, the stand-up teacher spoke very well, too detailed but also good.)

Props concept

Props: property, which is a JavaScript object.

  • propsIs the data that the caller passes to the component (similar to a function parameter), andstateIs data within a component that is managed by the component itself (similar to variables declared within a function).
  • propsIs not modifiable, allReactComponents must be protected as pure functionspropsNot changed. Due to thepropsAre passed in, and they cannot be changed, so we can use any onlypropsReactComponents aspureComponentThat is, with the same input, it will always render the same output.
class Person extends React.Component {
  render() {
    const { name, age, sex } = this.props;
    return (
      <ul>
        <li>Name: {name}</li>
        <li>Gender: {sex}</li>
        <li>Age: {age}</li>
      </ul>
    );
  }
}
ReactDOM.render(<Person name="jerry" age="19" sex="Male" />.document.getElementById("test1"));
ReactDOM.render(<Person name="tom" age="18" sex="Female" />.document.getElementById("test2"));
ReactDOM.render(<Person name="sophia" age="24" sex="Female" />.document.getElementById("test3"));
Copy the code

Review the three-point operator

let arr1 = [1.3.5.7.9];
let arr2 = [2.4.6.8.10];
console.log('Expand array'. arr1);// Expand the array
let arr3 = [arr1, arr2]; // Array merge
console.log('Array merge', arr3);
let copyArr = [...arr1]; // Array copy
console.log('Array copy', copyArr);

// Function arguments
function log(x, y, z) {
   console.log('Function argument', x, y, z)
}
let args = [1.1.1.1.1]; log(... args);// Function line argument
function sum(. numbers) {
  return numbers.reduce((pre, cur) = > {
    returnpre + cur; })}console.log('Function line parameter', sum(1.2.3.4));

let obj1 = {a: 1.b: 2};
let obj2 = {c: 3.d: 4};
letobj3 = {... obj1, ... obj2};// Object merge
console.log('Object merge', obj3);
letcopyObj = {... obj1};// Object replication
console.log('Object Copy', copyObj);

let person = {name: 'tom'.aget: '18'};
console.log('Object expansion'. person);// Object expansion failed
Copy the code

The above code describes most of the three operators: array expansion, array merge, array copy, object merge, object copy, function arguments, function parameters…

However, after testing, it was found that the object expansion failed. It can be seen that the object cannot be expanded by writing the expansion operator directly. It is necessary to copy the object with a layer of curly braces. So: the three-point operator cannot directly traverse an object, but the three-point operator can directly traverse an array and output it as a string of characters.

Batch transfer props

When we need to pass props in batches, we can use the three-point operator to do this:

const p = {name: 'sophia'.age: 24.sex: 'woman'}

ReactDOM.render(<Person {. p} / >.document.getElementById("test"));
Copy the code

Note, however, that {… P} is not equivalent to the use of object expansion failure mentioned in the previous section. The React rendering function uses curly braces as delimiters. P.

But didn’t we mention above that the three-point operator cannot directly traverse an object? React + Babel actually allows the expansion operator to expand an object in the tag attribute pass, but native JS doesn’t.

Restrict props

// Introduce prop-types package: called by PropTypes
class Person extends React.Component {
  // Restrict the type and necessity of the tag attributes
  static propTypes = {
    name: PropTypes.string.isRequired,
    sex: PropTypes.string,
    age: PropTypes.number,
    speak: PropTypes.func, // Function is a keyword, so the built-in type is func
  }
  
  // Specify the default tag attribute value
  static defaultProps = {
    sex: 'woman'.age: 24
  }

  render() {
    const { name, age, sex } = this.props;
    return (
      <ul>
        <li>Name: {name}</li>
        <li>Gender: {sex}</li>
        <li>Age: {age}</li>
      </ul>); }}const p = {name: 'sophia'.age: 24.sex: 'woman'}
ReactDOM.render(<Person {. p} / >.document.getElementById("test"));

ReactDOM.render(<Person name="jerry" age={19} speak={speak} />.document.getElementById("test1"));
ReactDOM.render(<Person name="tom" age={18} sex="Female" />.document.getElementById("test2"));
ReactDOM.render(<Person name="sophia" age={24} sex="Female" />.document.getElementById("test3"));
Copy the code

The restrictions on props could have been defined outside of the Person class using Person.propTypes and Person.defaultProps. A class knows that assigning a property directly to a class is actually a static property of the class, so it can be defined using the static keyword.

Props in the constructor

The first thing we need to know is what does a constructor do?

The two functions of constructors are specified on the website, but we can substitute them in a more convenient way:

  • It’s directly in the classstate = {isHot: false}Initialize state.
  • Coordinate arrow functions with assignment statements directly in the classchangeWeather = () => {... }Implement custom methods.

So the constructor can actually be omitted

So what does super(props) do?

class Person extends React.Component {
  constructor(props) {
    super(props)
    console.log(this.props) // Output defines attributes
    console.log(this.props) // This can be omitted
  }
  
  // constructor() {
  // super()
  // console.log(this.props) // undefined
  // }
}
Copy the code

As you can see from the example above, whether the constructor receives props and passes it to super depends on whether you want to access props through this in the constructor.

If state is not initialized or method binding is not performed, there is no need to implement a constructor for the React component.

In fact, custom constructors are rarely needed in development, so you don’t need to write them if you can.

Functional components use props

The three properties of a component instance are: state, props, and refs. Since an instance of a class component has this, you can use this to access state, props, and refs.

For a functional component, it does not have this, so it cannot use state, refs, but it can still use props because functions can accept parameters.

function Person (props) {
  const { name, age, sex } = props;
  return (
    <ul>
      <li>Name: {name}</li>
      <li>Gender: {sex}</li>
      <li>Age: {age}</li>
    </ul>
  );
}


const p = {name: 'sophia'.age: 24.sex: 'woman'}
ReactDOM.render(<Person {. p} / >.document.getElementById("test"));

ReactDOM.render(<Person name="jerry" age={19} speak={speak} />.document.getElementById("test1"));
ReactDOM.render(<Person name="tom" age={18} sex="Female" />.document.getElementById("test2"));
ReactDOM.render(<Person name="sophia" age={24} sex="Female" />.document.getElementById("test3"));
Copy the code