This is the sixth day of my participation in the August More text Challenge. For details, see: August More Text Challenge

1. Component communication

A component is a separate, closed unit, and by default only its own data can be used. In componentization, we break down a complete function into multiple components to better complete the function of the entire application. However, there is no way to avoid sharing data between multiple components, so the process of breaking isolation is called component communication.

2.props

2.1 Props

  • The component is enclosed and to receive external data should be implemented using props
  • The props function is to receive data passed to a component
  • Pass data: Add attributes to component labels
<Hello name="jack" age={19} / >Copy the code
  • Receiving data: Function components receive data with the props argument, and class components receive data with this.props

Function component

function Hello(props){
	return (
	 <div>Received data: {props. Name}</div>)}Copy the code

Class components

class Hello extends React.Component{
	render(){
		return(
		 <div>Received data :{this.props. Age}</div>)}}Copy the code

Example 1: Function component We print props as an object

//2 Receive data
const Hello = props= >{
  console.log(props)
  return(
    <div>
      <h1>props:{props.name}</h1>
    </div>)}// 1 Pass data
ReactDOM.render(<Hello name="jack" />.document.getElementById('root'))
Copy the code

Example 2: Class components

//2 Receive data
class Hello extends React.Component{
  render(){
    console.log(this.props)
    return(
      <div>
        <h1>props:{this.props.name}</h1>
      </div>)}}// 1 Pass data
ReactDOM.render(<Hello name="jack" />.document.getElementById('root'))
Copy the code

2.2 characteristics of props

  • You can pass any type to a component
/ / character
<Hello age="19"/>
/ / numeric
<Hello age={10} />
/ / array
<Hello colors=['red', 'green', 'pink'] / >
/ / function
<Hello fn={()= >Console. log('this is function ')}/>
Copy the code

To pass a function in a function component, you can call the function passed in the component, props.fn().

const Hello = props= >{
  props.fn()
  return(
    <div>
      <h1>props:{props.name}</h1>
    </div>)}// 1 Pass data
ReactDOM.render(<Hello name="jack" fn={()= >Console. log('this is function ')} />.document.getElementById('root'))
Copy the code

In the class component

class Hello extends React.Component{
  constructor(props){
    super(props)
    props.fn()
  }
  render(){
    console.log(this.props.fn);
    return(
      <div>
        <h1>props:{this.props.name}</h1>
      </div>)}}// 1 Pass data
ReactDOM.render(<Hello name="jack" fn={()= >Console. log('this is function ')} />.document.getElementById('root'))
Copy the code

Pass JSX

<Hello name="jack" 
tag = {<p>This is a label</p>}
fn={() = >console.log('This is function')} / >,document.getElementById('root'))
Copy the code
  • Props is a read-only object. It can only read the values of properties. It cannot modify the object. An error is reported after modification
const Hello = props= >{
  props.fn()
  props.name="sssss"
  return(
    <div>
      <h1>props:{props.name}</h1>
      {props.tag}
    </div>)}Copy the code

  • Note: When using a class component, if you write a constructor, you should pass the props to super(). Otherwise, you cannot get props in the constructor or get them
class Hello extends React.Component{
	constructor(props){
	 // We recommend passing props to the superclass constructor
		super(props)
		 //console.log(this.props)
		 //console.log(props)
	}
	render(){
		console.log(this.props)
		return <div>{this.props.age}</div>}}Copy the code

3. There are three ways for components to communicate

3.1 Passing a parent component to a child Component

  1. The parent component provides the state data to pass
  2. Adds a property to the child component with the value of the data in state
  3. The child component uses props to receive data passed from the parent component
class Parent extends React.Component{
  state={
    lastName:"wang"
  }
  render(){
    return(
      <div style={{background:"red}} ">The parent component:<Child name={this.state.lastName}/>
      </div>)}}const Child = (props) = >{
  console.log(props)
  return(
    <div style={{background:"skyblue}} ">
      <p>Child component: {props. Name}</p>
    </div>)}// 1 Pass data
ReactDOM.render(<Parent/>.document.getElementById('root'))
Copy the code

3.2 Child Component passes data to parent component

The parent component provides the callback, the child component calls it, and the data to be passed as the parameters of the callback function

  1. The parent component provides a callback function (to receive data)
  2. Pass this function as the value of the property to the child component
  3. The child component calls the callback function with the props
  4. Pass the data of the child component as a parameter to the callback function
/** - Parent component */
class Parent extends React.Component{
  state ={
    parentMsg : ' '
  }
  // Provide a callback function to receive data
  getData = (data) = >{
    console.log("Accepted data",data)
    this.setState({parentMsg:data})
  }
  render(){
    return(
      <div style={{background:"red}} ">Parent: {this.state.parentMsg}<Child getData={this.getData}/>
      </div>)}}/** - subcomponent */
class Child extends React.Component{
  state ={
    childMsg :'react'
  }
  handelClick = () = >{
    this.props.getData(this.state.childMsg)
  }
  render(){
    return(
      <div style={{background:"skyblue}} ">
         <button onClick={this.handelClick}>button</button>
      </div>)}}Copy the code

3.3 Sibling Components

  • The shared state is promoted to the nearest public parent, which manages the state

  • Thought: State of uplift
  • Common parent responsibilities: 1. Provide shared state. 2. Provide methods to operate on shared state
  • The child component to communicate only needs to receive state or methods that operate state via props
class Counter extends React.Component {
  // Provide the shared state
  state ={
    count:0
  }
  // Provides a way to modify the state
  Add = () = >{
    this.setState({
      count:this.state.count+1})}render() {
    return (
      <div>
        <Child1 count={this.state.count}/>
        <Child2 Add={this.Add}/>
      </div>)}}const Child1 = (props) = > {
  return <h1>Counter: {props. Count}</h1>
}
const Child2 = (props) = > {
  return <button onClick={()= >{props.Add()}}>+1</button>
}

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