Three major attributes of React components: props

1. Understand

In React, "props" is short for "properties" and is a mechanism for passing data and configuration information to components. Props are one of the main ways of communicating between React components.

2. Purpose

It has the following main uses:

  1. Pass data: Through props, parent components can pass data to child components. Subcomponents can obtain this data by accessing props and use it inside the component. This allows data to be passed from one component to another, allowing for dynamic rendering and display of different content.

  2. Configuration component: Through props, you can pass configuration information to the component to customize it according to different needs. For example, you can pass text, styles, and click handlers to a generic button component so that the button can be reused in different contexts and rendered differently.

  3. Inter-component communication: In a React application, different components may need to communicate and collaborate. By using props, you can pass data from one component to another, enabling communication and data transfer between components.

  4. Dynamic rendering: Using props, you can dynamically render components based on different data and states. This allows you to render a component's content differently based on user actions, changes in data, or changes in application state.

  5. One-way data flow: In React, the data flow is one-way, that is, data is passed from the parent component to the child component through props, and the child component cannot directly modify the parent component. data. This helps maintain application predictability and maintainability.

  6. Performance optimization: Using props, React can effectively compare and update virtual DOM. When props change, React can intelligently decide whether the component needs to be re-rendered, thus optimizing in terms of performance.

In short, props are an important mechanism for transferring data and configuration information between React components, which helps build componentized applications that are composable, reusable, and maintainable. By using props, you can pass data from parent components to child components, enabling communication and data flow between components.

3. Use

3.1. Subclasses use props defined by the parent class

When a child component needs to use props of the parent component, you only need to access the data passed by the parent component through this.props in the child component. Here is an example using props from the parent component:

import React, {
    
     Component } from 'react';

// 父组件
class ParentComponent extends Component {
    
    
  constructor(props) {
    
    
    super(props);
    this.state = {
    
    
      message: "Hello from parent!",
    };
  }

  render() {
    
    
    return (
      <div>
        <ChildComponent message={
    
    this.state.message} />
      </div>
    );
  }
}

// 子组件
class ChildComponent extends Component {
    
    
  render() {
    
    
    // 子组件通过 this.props.message 访问父组件传递的数据
    return (
      <div>
        <p>{
    
    this.props.message}</p>
      </div>
    );
  }
}

export default ParentComponent;

In the above example, ParentComponent is the parent component, which contains a state named message and then passes this state as in the child component. . Access and display this message through props passed to child componentChildComponentthis.props.message

WhenParentComponent renders, it passes the current state of message to ChildComponent and then ChildComponent Use thismessage to render your own content. This is an example of how a child component can use the parent component's props data.

It should be noted that if you use function components to write sub-components, you do not need to use this.props, but can directly access props, as shown below:

import React from 'react';

function ChildComponent(props) {
    
    
  // 在函数组件中,可以直接通过 props.message 访问父组件传递的数据
  return (
    <div>
      <p>{
    
    props.message}</p>
    </div>
  );
}

export default ChildComponent;

This is how props is accessed in a function component. Whether using class or function components, child components can easily use the props passed by the parent component.

3.2. The child function uses the props of the parent function

In React, use props to pass data and configuration information to child components through parent components. Here are the basic steps on how to use props:

  1. Define parent component: First, you need to create a parent component, usually a component that contains the data you want to pass.

  2. Set props in the parent component: In the JSX of the parent component, use attributes to pass data to the child component. For example:

// ParentComponent.js
import React from 'react';
import ChildComponent from './ChildComponent';

function ParentComponent() {
    
    
  const message = "Hello from parent!";
  
  return (
    <div>
      <ChildComponent message={
    
    message} />
    </div>
  );
}

export default ParentComponent;
  1. Receive props in the subcomponent: In the code of the subcomponent, receive the passed props data through function parameters. These props will be passed to the component function as objects.
// ChildComponent.js
import React from 'react';

function ChildComponent(props) {
    
    
  return (
    <div>
      <p>{
    
    props.message}</p>
    </div>
  );
}

export default ChildComponent;

In the above example, the parent componentParentComponent passes data named message to the child componentChildComponent . The passed data is accessed through props.message in the child component.

It should be noted that props is read-only and child components cannot modify them directly. They remain unchanged throughout the lifetime of the component. If you need to make modifications in the subcomponent, you can convert the data into a state (state) or use a callback function.

In addition, other types of data can be passed, such as functions, objects, etc., as well as multiple props. In the child component, you can access this passed data through the props object.

To sum up, using props is an important mechanism for passing data from parent components to child components for communication and data transfer between components.

3.3. Dynamically set the values ​​in props

The data within dynamic settingsprops is usually generated by generating different data according to different situations in the parent component, and then passing these data as props to child components. This enables dynamically updating the content of child components based on the state of the application or user interaction.

The following is an example of how to dynamically set the data within props:

// ParentComponent.js
import React, {
    
     useState } from 'react';
import ChildComponent from './ChildComponent';

function ParentComponent() {
    
    
  const [count, setCount] = useState(0);
  
  // 根据 count 动态生成 message
  const message = `Count is ${
      
      count}`;
  
  return (
    <div>
      <button onClick={
    
    () => setCount(count + 1)}>Increment Count</button>
      <ChildComponent message={
    
    message} />
    </div>
  );
}

export default ParentComponent;
// ChildComponent.js
import React from 'react';

function ChildComponent(props) {
    
    
  return (
    <div>
      <p>{
    
    props.message}</p>
    </div>
  );
}

export default ChildComponent;

In the example above, there is a state in the parent component ParentComponent that is incremented every time the button is clicked. According to this , the parent component dynamically generates a string, and then passes this string to the child component as < /span>. . The child component will display this dynamically generated countcountmessagepropsChildComponentmessage

In a similar way, you can dynamically generate different data based on the application's state, user input, API response, etc., and then pass it to the sub-component to dynamically update the content of the sub-component. This pattern is very useful in building dynamic and interactive applications.

3.4. Use state and props together

State is generally initialized using parameters in props.

demonstrates not using its own state in the child component, but directly using the props passed by the parent component:

import React, {
    
     Component } from 'react';

class ParentComponent extends Component {
    
    
  constructor(props) {
    
    
    super(props);
    this.state = {
    
    
      count: props.initialCount,
    };
  }

  incrementCount = () => {
    
    
    this.setState((prevState) => ({
    
    
      count: prevState.count + 1,
    }));
  };

  render() {
    
    
    return (
      <div>
        <p>Parent Count: {
    
    this.state.count}</p>
        <ChildComponent count={
    
    this.state.count} incrementCount={
    
    this.incrementCount} />
      </div>
    );
  }
}

function ChildComponent(props) {
    
    
  return (
    <div>
      <p>Child Count from Parent: {
    
    props.count}</p>
      <button onClick={
    
    props.incrementCount}>Increment Parent Count</button>
    </div>
  );
}

class App extends Component {
    
    
  render() {
    
    
    return <ParentComponent initialCount={
    
    5} />;
  }
}

export default App;

ChildComponent directly uses the count passed from the parent component, and updates the parent component's state by calling the method via props . This method is more concise and clear, and is suitable for situations where the child component only needs to access the data passed by the parent component without maintaining independent state. incrementCount

3.5. Examples where props changes can notify state changes

Yes, when of the child component is initialized through props, if in the parent component changes , these changes are not automatically reflected in the child component's . The sub-component's is only initialized by when the component is initialized. Subsequent changes will not automatically update the sub-component's < /span>. statepropsstatestatepropspropsstate

If you want the child component to be able to update its own after receiving a new props, you can use Lifecycle method to listen for changes in and manually update the child component's . Here's an example:statecomponentDidUpdatepropsstate

import React, {
    
     Component } from 'react';

class ChildComponent extends Component {
    
    
  constructor(props) {
    
    
    super(props);
    this.state = {
    
    
      localData: props.data,
    };
  }

  componentDidUpdate(prevProps) {
    
    
    // 在 props 更新时更新子组件的内部状态
    if (prevProps.data !== this.props.data) {
    
    
      this.setState({
    
    
        localData: this.props.data,
      });
    }
  }

  render() {
    
    
    return (
      <div>
        <p>Local Data in Child: {
    
    this.state.localData}</p>
      </div>
    );
  }
}

class ParentComponent extends Component {
    
    
  constructor(props) {
    
    
    super(props);
    this.state = {
    
    
      data: 'Initial Data',
    };
  }

  changeData = () => {
    
    
    this.setState({
    
    
      data: 'Updated Data',
    });
  };

  render() {
    
    
    return (
      <div>
        <button onClick={
    
    this.changeData}>Change Data</button>
        <ChildComponent data={
    
    this.state.data} />
      </div>
    );
  }
}

export default ParentComponent;

In the above example, when the parent component's data changes, clicking the button will trigger the parent component's changeData method, which updates the parent component's data. Although the parent component's data changes, the child component's state will not update automatically. The child component listens to componentDidUpdate and updates its own when the parent component's data changes. state

It is important to note that in order to avoid unnecessarystate updates, you should only manually update subcomponentsstate when needed, not when Updated every time props changes.

4. Pass properties (props) to components

In React, there are multiple ways to pass props to components. Here are some examples:

  1. Pass the value directly: The simplest way is to pass the attribute value directly to the component.
<MyComponent name="John" age={30} />
  1. Passing values ​​using variables: You can pass the value of a variable to a component as a property.
const name = "John";
const age = 30;
<MyComponent name={name} age={age} />
  1. Use an object to pass multiple properties: If you want to pass multiple properties, you can organize them into an object and pass them to the component.
const person = {
  name: "John",
  age: 30,
};
<MyComponent person={person} />
  1. Use JavaScript expressions to pass values: You can use JavaScript expressions in attribute values.
<MyComponent name={2 + 2} age={getAge()} />
  1. Passing values ​​using conditional expressions: You can pass attributes dynamically based on conditions.
const isAdult = true;
<MyComponent name="John" age={isAdult ? 30 : 15} />
  1. Use the map function to pass multiple components: If you want to pass multiple components of the same type, you can use the map function to generate them.
const names = ["John", "Alice", "Bob"];
const components = names.map((name, index) => <MyComponent key={index} name={name} />);
  1. Destructuring by value

If you want to pass properties (props) through object destructuring, you can pass an object containing multiple properties in the parent component, and then use object destructuring in the child component to get these properties. Here is an example:

First, define an object containing multiple properties in the parent component and pass the object to the child component:

// ParentComponent.js
import React from 'react';
import ChildComponent from './ChildComponent';

function ParentComponent() {
  const person = {
    name: "John",
    age: 30,
    city: "New York",
  };

  return (
    <div>
      <ChildComponent {...person} />
    </div>
  );
}

export default ParentComponent;

In this example, ParentComponent passes an object named person as a property to ChildComponent and uses {...person} syntax to pass the object's property destructuring to child components.

Then, in the child component, you can use object destructuring to get the passed properties:

// ChildComponent.js
import React from 'react';

function ChildComponent({ name, age, city }) {
  return (
    <div>
      <p>Name: {name}</p>
      <p>Age: {age}</p>
      <p>City: {city}</p>
    </div>
  );
}

export default ChildComponent;

InChildComponent, we use object destructuring to deconstruct the properties passed by the parent component into name, age and city. These variables can then be used directly to access and display the values ​​of these properties.

This approach makes the code more concise and readable, especially when you need to pass multiple properties and use them in child components.

Reference address

Travel:https://juejin.cn/post/7015402441298411533

https://www.bilibili.com/video/BV1wy4y1D7JT/?spm_id_from=333.337.search-card.all.click&vd_source=8ac97496e3a9e47d15f8bdfb630e596a

Guess you like

Origin blog.csdn.net/weixin_35691921/article/details/132402812