learning target
- Introduction to component communication and why there is component communication
- Component props
- Three ways of component communication Father-to-son-to-father-to-sibling components
- Context component communication
- props in-depth
- todomvc
Component communication
Components are independent and closed units. By default, only the component's own data can be used. In the process of componentization, we split a complete function
into multiple components to better complete the functions of the entire application. In this process, it is inevitable to share some data between multiple components
. In order to realize these functions, it is necessary to break the independent closure of components and allow them to communicate with the outside world. This process is component communication .
Vernacular: One component uses the state of another component
props
- Components are closed, and to receive external data should be implemented through props
- The role of props: receive the data passed to the component
- Pass data: add attributes to component tags
- Receive data: function components receive data through parameter props, and class components receive data through this.props
Function component communication
Subassembly
function Hello(props) {
console.log(props)
return (
<div>接收到数据:{
props.name}</div>
)
}
parent component
<Hello name="jack" age={
19} />
class component communication
Subassembly
class Hello extends React.Component {
render() {
return (
<div>接收到的数据:{
this.props.age}</div>
)
}
}
parent component
<Hello name="jack" age={
19} />
The characteristics of props
-
Any type of data can be passed to the component
-
props is read-only, does not allow modification of props data, one-way data flow
-
Note: When used in class components, props need to be passed to super() , otherwise the constructor cannot get props
class Hello extends React.Component {
constructor(props) {
// 推荐将props传递给父类构造函数
super(props)
}
render() {
return <div>接收到的数据:{
this.props.age}</div>
}
}
Three ways of component communication
- father to son
- child's father
- non father and son
father to son
- The parent component provides the state data to be passed
- Add an attribute to the subcomponent tag, the value is the data in the state
- The child component receives the data passed in the parent component through props
The parent component provides data and passes it to the child component
class Parent extends React.Component {
state = {
lastName: '王' }
render() {
return (
<div>
传递数据给子组件:<Child name={
this.state.lastName} />
</div>
)
}
}
Subcomponent receives data
function Child(props) {
return <div>子组件接收到数据:{
props.name}</div>
}
Comment list case
child's father
Idea: Using the callback function, the parent component provides a callback, the child component calls, and the data to be passed is used as the parameter of the callback function.
- The parent component provides a callback function (for receiving data)
- Pass the function as the value of the property to the child component
- The child component calls the callback function through props
- Pass the child component's data as a parameter to the callback function
The parent component provides the function and passes it the string
class Parent extends React.Component {
getChildMsg = (msg) => {
console.log('接收到子组件数据', msg)
}
render() {
return (
<div>
子组件:<Child getMsg={
this.getChildMsg} />
</div>
)
}
}
The child component receives the function and calls
class Child extends React.Component {
state = {
childMsg: 'React' }
handleClick = () => {
this.props.getMsg(this.state.childMsg)
}
return (
<button onClick={
this.handleClick}>点我,给父组件传递数据</button>
)
}
Note: this in the callback function points to the problem!
brother
- Promote shared state to the nearest common parent component, which manages this state
- Thoughts: Status Improvement
- Public Parent Component Responsibilities:
- Provide shared status
- Provides methods for manipulating shared state
- Subcomponents that want to communicate only need to receive state or a method of manipulating state via props
Before status promotion
After status promotion
Component communication-context
basic concept
Thinking: How should the App component pass data to the Child component?
Processing method: use props to pass down layer-by-layer components (complex)
Better Posture: Using Context
Role: Pass data across components (such as: theme, language, etc.)
Implementation ideas
- Call React.createContext() to create Provider (provide data) and Consumer (consume data) two components.
const {
Provider, Consumer } = React.createContext()
- Use Provider component as parent node.
<Provider>
<div className="App">
<Child1 />
</div>
</Provider>
- Set the value attribute, indicating the data to be passed.
<Provider value="pink">
- Call the Consumer component to receive data.
<Consumer>
{
data => <span>data参数表示接收到的数据 -- {
data}</span>}
</Consumer>
Summarize:
- If two components are distant relatives (for example, nested multiple layers), you can use Context to realize component communication
- Context provides two components: Provider and Consumer
- Provider component: used to provide data
- Consumer component: used to consume data
props in-depth
children attribute
children attribute: Indicates the child nodes of the component, as long as the component has child nodes, props has this attribute
The children property is the same as normal props, and the value can be any value (text, React element, component, or even a function)
function Hello(props) {
return (
<div>
该组件的子节点:{
props.children}
</div>
)
}
<Hello>我是子节点</Hello>
props validation
Purpose: Verify the data type of the received props and increase the robustness of the component
For components, props are foreign, and there is no guarantee of what format data will be passed in by component users
If the format of the incoming data is incorrect, it may cause an error within the component. The user of the component cannot clearly know the cause of the error.
props verification allows to agree on the format and type of props when creating components
Function: It is stipulated that the type of props received must be an array. If it is not an array, an error will be reported to increase the robustness of the component.
Steps for usage
-
Install package prop-types (yarn add prop-types / npm i props-types)
-
Import the prop-types package
-
Use component name.propTypes = {} to add validation rules to component props
-
Validation rules are specified through the PropTypes object
import PropTypes from 'prop-types'
function App(props) {
return (
<h1>Hi, {
props.colors}</h1>
)
}
App.propTypes = {
// 约定colors属性为array类型
// 如果类型不对,则报出明确错误,便于分析错误原因
colors: PropTypes.array
}
binding rules
- Common types: array, bool, func, number, object, string
- React element type: element
- Required field: isRequired
- An object of a specific structure: shape({ })
// 常见类型
optionalFunc: PropTypes.func,
// 必选
requiredFunc: PropTypes.func.isRequired,
// 特定结构的对象
optionalObjectWithShape: PropTypes.shape({
color: PropTypes.string,
fontSize: PropTypes.number
})
props default value
Scenario: Paging component Number of items displayed on each page
Function: Set default values for props, which will take effect when props are not passed in
function App(props) {
return (
<div>
此处展示props的默认值:{
props.pageSize}
</div>
)
}
// 设置默认值
App.defaultProps = {
pageSize: 10
}
// 不传入pageSize属性
<App />
The static attribute of the class static
-
Instance members: attributes or methods called by instances,,, called instance members (attributes or methods)
-
Static members: properties or methods that can only be accessed through the class or constructor itself
class Person {
name = 'zs',
static age = 18
sayHi() {
console.log('哈哈')
}
static goodBye() {
console.log('byebye')
}
}
const p = new Person()
console.log(p.name)
p.sayHi()
console.log(Person.age)
Person.goodBye()