React passes parameters in several ways

React passes parameters in several ways

Passing parameters between parent and child components

The parent component passes the value to the child component, which can be achieved directly using this.props

In the parent component, add a custom property to the child component that needs to pass data, and in the child component, you can get the data passed by the parent component through this.props

// Parent component render() {
        return (
                // Use custom attributes to pass the method or parameter that needs to be passed <ShopUi toson={this.state}></ShopUi>
            )
    } 

//Subcomponent//You can get the data passed by the parent component through this.props.toson

If you need to pass it to the grandchild component, just pass it through the custom attribute in the child component.

tograndson={this.props.toson}

The grandchild component obtains data through this.props.tograndson

If a child component passes a value to a parent component, you need to set the receiving function and state in the parent component, and pass the function name to the child component through props.

That is, the method of passing the parent component to the child component and calling it in the child component

//Grandson component export default class Grandson extends Component {
    render(){
        return (
            <div style={{border: "1px solid red",margin: "10px"}}>
        {this.props.name}:
                <select onChange={this.props.handleSelect}>
                    <option value="Male">Male</option>
                    <option value="Female">Female</option>
                </select>
            </div>
        )
    }
};
 
//Child component export default class Child extends Component {
    render(){
        return (
            <div style={{border: "1px solid green",margin: "10px"}}>
                {this.props.name}: <input onChange={this.props.handleVal}/>
                <Grandson name="Gender" handleSelect={this.props.handleSelect}/>
            </div>
        )
    }
};
 
//Parent component export default class Parent extends Component {
 
    constructor(props){
        super(props)
        this.state={
            username: '',
            sex: ''
        }   
    },
    handleVal(event){
        this.setState({username: event.target.value});
    },
    handleSelect(value) {
        this.setState({sex: event.target.value});
    },
    render(){
        return (
            <div style={{border: "1px solid #000",padding: "10px"}}>
                <div>User name: {this.state.username}</div>
                <div>User gender: {this.state.sex}</div>
                <Child name="Name" handleVal={this.handleVal} handleSelect={this.handleSelect}/>
            </div>
        )
    }
}

Some time ago someone asked me this question: What is the use of super() in constructor?

To summarize:

If you want to use this in the constructor of a subclass, you must call the parent class constructor, otherwise you will not get this.

So the question is, how to call the constructor of the parent class? Via super()

If you want to use the parameters passed by the parent component in the constructor, you must pass the parameters to the parent component's constructor when calling the parent component's super.

If you don’t use this or parameters in the constructor, you don’t need super; React already binds this and props for you.

Routing parameters

Installnpm install react-router-dom --save-dev

Define routes (usually placed outside)

 <HashRouter> 
    <Switch> 
        <Route exact path="/" component={Home}/> 
        <Route exact path="/detail" component={Detail}/> 
    </Switch> 
</HashRouter> 

When the page jumps

<li onClick={el => this.props.history.push({
   pathname:'/detail',
     state:{id:3}
})}
>
</li>

Receive the passed data through this.props.history.location

There may be a problem with route parameter passing, that is, only the component mounted when the route is defined will have the location history match in props

The component mounted on the route is usually Container.js. Generally, we will separate the UI.js component and click and jump in it. There is no location history match in the props of the UI component.

You need to use the high-level component withRouter

Status Improvement

Promote the state that multiple components need to share to the common parent component closest to them, and then the parent component distributes it to the child components through props

context

When a component saves a state in its own context, all descendant components under that component can access this state without the need for intermediate components to pass it, but the parent component of this component cannot access it.

class Index extends Component {
  static childContextTypes = {
    themeColor: PropTypes.string
  }

  constructor () {
    super()
    this.state = { themeColor: 'red' }
  }

  getChildContext () {
    return { themeColor: this.state.themeColor }
  }

  render () {
    return (
      <div>
        <Header />
        <Main />
      </div>
    )
  }
}

Components that provide context by passing properties to all descendant components through getChildContext() must provide childContextTypes as a declaration and validation of the context.

class Title extends Component {
  static contextTypes = {
    themeColor: PropTypes.string
  }

  render () {
    return (
      <h1 style={{ color: this.context.themeColor }}>Title</h1>
    )
  }
}

If a subcomponent wants to get the content in the context, it must write contextTypes to declare and verify the type of state you need to get. It is also required. If you don't write it, you can't get the state in the context.
Title wants to get themeColor, which is a string, so we declare it in contextTypes.

Introducing redux

Redux provides a predictable state management mechanism for React

Redux stores the entire application state in the store, which stores a state tree

Components can dispatch actions to the store instead of notifying other components directly.

Other components can refresh their views by subscribing to the state in the store.

This is the end of this article about several ways to pass parameters in React. For more relevant content about passing parameters in React, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Parameter passing between react components (detailed explanation)
  • Let's talk about the issue of passing parameters to React onClick

<<:  Perfect solution to mysql cannot start after phpstudy is installed (no need to delete the original database, no need to change any configuration, no need to change the port) direct coexistence

>>:  How to upgrade CentOS7 to CentOS8 (detailed steps)

Recommend

HTML special character conversion table

character Decimal Character Number Entity Name --...

Learn v-model and its modifiers in one article

Table of contents Preface Modifiers of v-model: l...

How to find and delete duplicate records in MySQL

Hello everyone, I am Tony, a teacher who only tal...

Detailed explanation of the basic functions and usage of MySQL foreign keys

This article uses examples to illustrate the basi...

The final solution to Chrome's minimum font size limit of 12px

I believe that many users who make websites will ...

CentOS 6 Compile and install ZLMediaKit analysis

Install ZLMediaKit on centos6 The author of ZLMed...

How to upload and download files between Linux server and Windows system

Background: Linux server file upload and download...

Summary of MySQL database and table sharding

During project development, our database data is ...

How to simulate enumeration with JS

Preface In current JavaScript, there is no concep...

MySQL 8.0.18 deployment and installation tutorial under Windows 7

1. Preliminary preparation (windows7+mysql-8.0.18...

Use PS to create an xhtml+css website homepage in two minutes

There are too many articles about xhtml+css websi...

Vue+ssh framework to realize online chat

This article shares the specific code of Vue+ssh ...

Detailed explanation of props and context parameters of SetUp function in Vue3

1. The first parameter props of the setUp functio...

Sample code for generating QR code using js

Some time ago, the project needed to develop the ...