React’s componentization makes communication between components very important. This article briefly introduces some common react components. Redux is also a component management method, but redux state management covers a lot of topics, so I’ll cover it briefly here, and I’ll cover it in more detail later.
The parent component communicates with the child component
React data flows are one-way. The most common way is to pass values from parent components to child components through props.
Examples (key sections are annotated) :
We make a simple case of choosing a commodity and changing the price.
Class Parents extends Component {// Constructorconstructor() { super(); // set state this.state = {price: 0}; } clickGoods(e) {// Update state this.setState({price: e}); } / / renderingrender() {
let { price } = this.state;
return( <div> <button onClick={this.clickGoods1.bind(this)}>goods1</button> <button OnClick ={this.clickGoods2.bind(this)}>goods2</button> <Child price={price} /> </div>); }}Copy the code
Subcomponent: The props property is used in the subcomponent to receive the passed data.
class Child extends Component {
render() {{/* here get */} from propsreturn<div> price: {this.props.price} </div>; }}Copy the code
Online code
Codesandbox. IO/s / 718 o454r6…
The child component communicates with the parent component
Next we reverse this and have the child component communicate to the parent. The basic idea of a child communicating with its parent is that the parent passes a function to the child and then gets the value passed by the child through the function’s callback. The parent component displays the price, the child component displays two buttons, and the child component passes the price to the parent.
Examples (key sections are annotated) :
The parent component
class Parents extends Component {
constructor() {
super();
this.state = {
price: 0
};
}
getItemPrice(e) {
this.setState({
price: e
});
}
render() {
return( <div> <div>price: {this.state.price}</div> {/* Pass a function to the Child component */} <Child getPrice={this.getitemprice.bind (this)} /> </div>); }}Copy the code
Child components
Class Child extends Component {clickGoods(e) {// Pass the value this.props. GetPrice (e); }render() {
return( <div> <button onClick={this.clickGoods.bind(this, 100)}>goods1</button> <button onClick={this.clickGoods.bind(this, 1000)}>goods2</button> </div> ); }}Copy the code
Online code
Codesandbox. IO/s / 718 o454r6…
Publisher and Subscriber Pattern (Context)
React props are passed from parent component to child component. Once the React props are passed from parent component to child component, they need to pass layer by layer. Context provides a new way for components to communicate (after version 16.3), share some data, and other components can read data from the context (similar to having a data source to which components can subscribe).
Method of use
The React. CreateContext () method
We can use createContext to create a context that can take a variable or object as a parameter (react uses object.is() to compare objects when they are parameters, somewhat affecting performance). This value is passed in as the default value of the context
const PriceContext = React.createContext('price')
Copy the code
So that creates a Context
The Provider component
Providers are used to create data sources. It is the parent component that provides the data source for all the child components. It takes a value as props to pass the value, and it changes the default value of the context. A provider can contain multiple Consumer components. If the Provider components are nested,
<PriceContext.Provider value={100}>
</PriceContext.Provider>
Copy the code
Consumer component
Consumer represents the component that accepts data and accepts a function as a child element. This function takes the value passed by the context and returns a react component. The Consumer component must be included in the Provider.
Price => <div>price: {price}</div>}</ pricecontext.consumer >Copy the code
The sample
In this section we try to pass directly from the parent to the grandchild, not through the child (directly from A to C, not through B).
// createContext const PriceContext = react.createcontext ('price'Class ClassA extends Component {constructor(){super() this.state={price:0}} // clickGoods(e) {this.setState({price:e})}render(){
const { price } = this.state
returnProvider value={price}> <button onClick={this.clickGoods.bind(this, 100)}>goods1</button> <button onClick={this.clickGoods.bind(this, 1000)}>goods2</button> <ClassB /> </ pricecontext.provider >)}} // class B extends Component {// Component B only refers to ClassC and does not pass valuesrender() {return(<div><span>price:</span><span><ClassC /></span></div>)}}render() {returnConsumer> {price =><span>{price}</span>}</ pricecontext.consumer >)} }Copy the code
Summary and understanding of context
A React app consists of many React components, some of which are nested and form a “component chain”. Context can be considered a component’s “scope” [3]. A root component, which defines a context, and components in its component chain can access variables or objects defined in the provider, as shown in the figure below. This is more like the concept of scope. Context can replace some of redux’s functionality in simple scenarios.
Online code
Codesandbox. IO/s / 718 o454r6…
Communication between sibling components
When components communicate with each other, the general idea is to find the same parent component. In this case, you can use props or context to pass data. Of course, some global mechanisms can also be used to implement communication, such as Redux, etc.
summary
This article mainly introduces three kinds of communication relationship between parent component and child component, child component and parent component, publisher and subscriber pattern (context), briefly describes the communication between sibling components. There are two ways to do this, using the props property and Context. I also introduced you to some context.
Reference:
[1] segmentfault.com/a/119000001…
[2] taobaofed.org/blog/2016/1…
[3] juejin. Cn/post / 684490…