solve the problem : Encapsulating behavior , For multiple components ( Sharing a piece of code among multiple components )

In the component props Property contains a "render" attribute ( This property is a method with a return value of element ), And then in the render In the method

Call the method , You can make the rendered content dynamic .

class Cat extends React.Component {
render() {
const mouse = this.props.mouse;
return (
<img src="./logo" style={{ position: 'absolute', left: mouse.x, top: mouse.y }} />
);
}
} class Mouse extends React.Component {
constructor(props) {
super(props);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.state = { x: 0, y: 0 };
} handleMouseMove(event) {
this.setState({
x: event.clientX,
y: event.clientY
});
} render() {
return (
<div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}>
{this.props.paint(this.state)}
// The following method is props.render Method ,mouse===this.state
// render={mouse => (
// <Cat mouse={mouse} />
// )}
</div>
);
}
} class MouseTracker extends React.Component {
render() {
return (
<div>
<h1>Move the mouse around!</h1>
<Mouse paint={mouse => (
<Cat mouse={mouse} />
)}/>
</div>
);
}
}

matters needing attention :

One 、 If this method is used , So in the component props Do not use "render" To define , Usually , I will use paint

Two 、 When the dynamic rendering component is integrated PureComponent When , You need to define this property as an instance method

reason : Because use React.PureComponent When ,React Shallow comparison will be used by default , The following code

if (this._compositeType === CompositeTypes.PureClass) {
shouldUpdate = !shallowEqual(prevProps, nextProps)
|| !shallowEqual(inst.state, nextState);
}

shallowEqual Will compare  Object.keys(state | props)  Is the length of the same , every last  key  Whether there are both , And is it a reference , That is, only the values of the first layer are compared , It's really shallow , So deep nested data can't be compared , Because of this , If in render Define a "render" Method properties , Because it's a method , So every call reder Will redefine the property , It's impossible to compare , It comes back every time false, Will cause unnecessary refresh .

The solution is as follows :

class MouseTracker extends React.Component {
constructor(props) {
super(props); // This binding ensures that `this.renderTheCat` always refers
// to the *same* function when we use it in render.
this.renderTheCat = this.renderTheCat.bind(this);
} renderTheCat(mouse) {
return <Cat mouse={mouse} />;
} render() {
return (
<div>
<h1>Move the mouse around!</h1>
<Mouse render={this.renderTheCat} />
</div>
);
}
}

Because after the component is instantiated , The internal method also becomes the instance method , Every time you call render after ”render“ The method called by the property is the instance method , The same location is referenced every time , So it doesn't make

React.PureComponent The advantage of the game disappears .

Reference resources :https://reactjs.org/docs/render-props.html

Study React series ( Ten )——Render Props More articles about

  1. Study React series ( Nine )—— Higher order function

    Definition : A higher-order component is a function , And the function takes a component as a parameter , And return a new component . ( As mentioned in the previous article, high-order components can be used to solve cross cutting problems ) One . Don't change the original components , Use combination class A extends Rea ...

  2. Study react series ( 8、 ... and )—— mixins transfer

    Let's first introduce mixins( Mix in ) Let's start with a piece of code : const mixin = function(obj, mixins) { const newObj = obj; newObj.prototype ...

  3. Study React series ( 7、 ... and )——Fragments、Portals、Error Boundaries And WEB Components

    React.Fragment portals Error Boundaries WEB Components React.Fragment Imagine a scene , Want to put td Wrappers are added to table In the middle , The code is as follows : class ...

  4. Study React series ( 5、 ... and )—— Optimize performance

    There are two ways to improve performance : One . Configuration level Two . The code level This article only considers from the code level : One . Avoid duplicate rendering Here's a word : When shouldComponentUpdate return false It doesn't trigger when it's on render The function is just ...

  5. Study React series ( Four )—— Controlled and uncontrolled components

    Controlled components : Control components by changing their states and properties Uncontrollable components : Directly through the bottom dom To control the components ( Specifically, it's through binding to the bottom dom It is realized by using the method of , for instance ref,onChange) Controlled components functio ...

  6. Study React series ( 3、 ... and )——Refs and Dom

    One . For the following scenarios : 1. Control the focus , Text selection , Or media control 2. Trigger the necessary animation 3. Integrating third parties dom library Two . Don't overuse ref If you want to pass ref To change state, So in another way - Variable promotion might be better . ...

  7. Study React series ( Two )—— Deepen understanding JSX

    1.JX It's actually React.createElement(component,props,...children) The grammar sugar of 2.JSX Judge whether it is react Components are based on the fact that the initial of the label is uppercase ( So you need to customize ...

  8. Study React series ( One )——React.Component Life cycle

    Mounting ( Only once ) The following methods are used when a component instance is being created and inserted into DOM Middle time call constructor() Generally used to initialize state And methods this binding componentWillMount() render( ...

  9. Study React series ( 6、 ... and )—— to update dom Details depend on the principle

    React to update dom The basis of : 1. Different types of elements It makes different trees 2. adopt render Method contains key Child elements of attributes , Developers can indicate which child elements may be stable . The update process : One . The root element type is different : used ...

Random recommendation

  1. RESTful Interface debugging sharing tool restc

    This tool comes from https://elemefe.github.io/restc/  Here to Abp It's packaged once 1. Add... To the project nuget package Abp.Web.Api.Restc 2. In the project Abp Modular D ...

  2. Ubuntu The problem with the wrong password

    Installed a Ubuntu, After starting, enter the terminal , Want to su root, Prompt for password , Entered the password many times ( My user password and root The password is the same ), Always Login incorrect. Then I entered the user name , Prompt for password , ...

  3. Beta edition —— The sixth sprint blog

    All I'm talking about is team 031402304 Chen Shen 031402342 Xu Lingling 031402337 Hu Xinying 03140241 Wang Tingting 031402203 Chen Qimin 031402209 Huang Weiwei 031402233 Zheng Yang ...

  4. Auto CAD 2013 The solution to the problem

    One . Problem presentation Auto CAD 2013 There was an error in using it :“ Security system ( Software lock license manager ) Not working or not properly installed .” Two . Analysis of the problem Many places on the Internet reprint such a method : 1) start-up Windows ...

  5. Cocos2d-x 3.0 Coordinate system details ( Reprint )

    Cocos2d-x 3.0 Coordinate system details Cocos2d-x Coordinate system and OpenGL The coordinate system is the same , They all originated in Cartesian coordinates . Cartesian coordinate system In Cartesian coordinate system, the origin of right hand system is defined in the lower left corner ,x towards the right ,y Up ,z outward ,OpenG ...

  6. setOpaque(true); Set control opacity

    setOpaque(true); Set control opacity setOpaque(false); Set control transparency

  7. ThinkPHP The foreground view implementation is similar to Yii Automatic verification of

    ThinkPHP model Class actually comes with this function You can write a base class inheritance Model Model layer code : <?php namespace Manager\Model; use Think\Model; cl ...

  8. 【MonkeyRunner Environment building 】

    One . To configure MonkeyRunner environment variable 1. First download a AndroidSDK, stay SDK In the directory of tools In the folder , Directly with MonkeyRunner 2. open MonkeyRunner The way : |-- ...

  9. linux bash Basic characteristics

    One .bash Basic characteristics (1) The function of command history history: environment variable HISTSIZE: Number of command history records HISTFILE: ~/.bash_history Each user has its own command history file ...

  10. pytorch Loading and saving models

    After the model is trained , We need to save the trained model as a file for testing , Or, for some reason, we need to continue the previous state training and save the model before , So how to be in PyTorch How to save and restore the model in ? Method 1 ( recommend ): The first method is also ...