[React] advanced component

Keywords: Javascript React

1, Introduction to component communication

Components are independent and closed units. By default, they can only use their own data. In the process of componentization, we split a complete function into multiple components to better complete the functions of the whole application. In this process, it is inevitable to share some data among multiple components. In order to realize these functions, it is necessary to break the independence and closure of components and let them communicate with the outside world. This process is component communication.

2, props of components

  • The component is closed. To receive external data, it should be implemented through props
  • props is used to receive data passed to components
  • Passing data: adding attributes to component labels
  • Receive data: function components receive data through parameter props, and class components receive data through this.props
  • props is an object
//Function component
const Hello = (props) => {
  // props is an object
  console.log(props)
  return(
    <div>
      <h1>props:{props.name}</h1>
    </div>
  )
}

//Class component
class Hello extends React.Component {
  render() {
    console.log(this.props)
    return(
      <div>
      <h1>name:{this.props.name}<br />age:{this.props.age}</h1>
    </div>
    )
  }
}
ReactDOM.render(<Hello name="rose" age={19} />,document.getElementById('root'))

characteristic

  1. Any type of data can be passed to the component.
  2. props is a read-only object. It can only read the value of the attribute and cannot modify the object.
  3. Note: when using class components, if the constructor is written, props should be passed to super(). Otherwise, props cannot be obtained in the constructor
class Hello extends React.Component {
  constructor(props){
    super(props)
    console.log(this.props)
  }
  render() {
    return(
      <div>
          <h1>name:{this.props.name}<br />age:{this.props.age}</h1>
      </div>
    )
  }
}
ReactDOM.render(<Hello name="rose" age={19} />,document.getElementById('root'))

Default value for props

Component name.defaultProps = {
​    Attribute name: value,
​	Attribute name: value
}

Type and necessity restrictions for attribute values

Component name.propTypes = {
​	Property name: PropTypes.data type.necessity(isRequired)
}

Case:

<div id="test1"></div>
<hr>
<div id="test2"></div>
<script type="text/babel">
class Person extends React.Component{
    constructor(props){
        super(props)
    }
    render(){
        return(
            <ul>
                <li>full name:{this.props.propsName}</li> 
                <li>Age:{this.props.propsAge}</li> 
                <li>Gender:{this.props.propsSex}</li>    
            </ul>
        )
    }
}
// Set the default value of the property
Person.defaultProps = {
    propsName:'Hutu',
    propsAge:6,
    propsSex:'male'
}

// Set the data type and necessity of the property
Person.propTypes = {
    propsName:PropTypes.string.isRequired,  //'propsName' must pass a string and must exist
    propsAge:PropTypes.number.isRequired  //'propage' must be a numeric type and must exist
}

ReactDOM.render(<Person />,document.getElementById('test1'))
ReactDOM.render(<Person propsName="Xiao Li" propsAge={30} propsSex="female" />,document.getElementById('test2'))

3, Three ways of component communication

1. The parent component passes data to the child component

  1. The parent component provides the state data to be passed.
  2. Add an attribute to the subcomponent tag with the value of data in state.
  3. The child component receives the data passed from the parent component through props.
class Parent extends React.Component {
  state = {lastName:'king'}  //Status: Data
  render() {
    return (
      <div>
        Parent component
        Pass to child components:<Child name={this.state.lastName} />
      </div>
    )
  }
}

function Child (props) {
  return <div>Data received by subcomponent:{props.name}</div>
}

ReactDOM.render(<Parent />,document.getElementById('root'))

2. The child component passes data to the parent component

Idea: using the callback function, the parent component provides a callback (not called), the child component calls, and takes the data to be transmitted as the parameters of the callback function.
Steps:

  1. The parent component provides a callback function to receive data
  2. Pass the function to the child component as an attribute value
  3. The subcomponent calls the callback function through props
  4. Pass the data in the subcomponent as a parameter to the callback function
// Parent component
class Parent extends React.Component {
  state={
    parentMsg:''
  }
  // Provides a callback function to receive data
  getChildMsg = (data) =>{
    console.log('Data received from subcomponent:',data)
    this.setState({
      parentMsg:data
    })
  }
  render(){
    return(
      <div>
        Parent component:{this.state.parentMsg}
        //Pass the function to the child component as an attribute value
        <Child getMsg={this.getChildMsg} />
      </div>
    )
  }
}
//Subcomponents
class Child extends React.Component {
  state={
    msg:'Play king'
  }
  handleClick = () =>{
    //The child component calls the callback function passed by the parent component
    this.props.getMsg(this.state.msg)
  }
  render(){
    return(
      <div>
        Subcomponents:
        <button onClick={this.handleClick}></button>
      </div>
    )
  }
}

4, Context

Role: transfer data across components
If two components are distant relatives (such as multi-layer nesting), Context can be used to realize component communication
Use steps:
1. Call React.createContext() to create two components: provider (providing data) and consumer (consuming data)
const { Provider, Consumer } = React.createContext ( )
2. Use the Provider component as the parent node

<Provider">
    <div>
       <Node />
    </div>
</Provider>

3. Set the value attribute to indicate the data to be transferred
4. Call the Consumer component to receive data

/*
Transfer data across components
*/
// 1. Create context to get two components
const {Provider,Consumer} = React.createContext()
class App extends React.Component {
  render(){
    return (
      // 2. Use the Provider component as the parent node.
      // 3. Set the value attribute to indicate the data to be transferred
      <Provider value="pink">
        <div>
          <Node />
        </div>
      </Provider>
    )
  }
}

const Node = props => {
  return (
    <div>
      <SubNode />
    </div>
  )
}

const SubNode = props => {
  return (
    <div>
      <Child />
    </div>
  )
}

const Child = props => {
  return(
    <div>
      // Call the Consumer component to use the callback function to receive data
      <Consumer>
          {data => <span>I am a child node -- {data}</span>}
      </Consumer>
    </div>
  )
}

ReactDOM.render(<App />,document.getElementById('root'))

Posted by pleisar on Thu, 14 Oct 2021 13:02:02 -0700