


A detailed introduction to controlled and uncontrolled components in React
This article mainly introduces the controlled components and uncontrolled components of React in-depth programming. Now I will share it with you and give you a reference.
There is not much information about controlled components and uncontrolled components on the official website and domestic websites. Some people think it is optional and don't care. This just shows the power of React to meet the needs of projects of different sizes. For example, if you just do a simple data display like ListView and capture the data, then a for loop and {} are enough. However, there are a large number of reports in the background system, and different forms are linked together. Without controlled components, it really won't work.
Controlled components and uncontrolled components are the entry points for React to process forms. From the perspective of React, the author must let the data control everything, or simply understand that the generation and update of the page must faithfully execute the JSX instructions.
But form elements have their own special features. Users can change the display of the interface through keyboard input and mouse selection. The change of the interface also means that some data has been changed. The more obvious ones are the value of the input, the innerHTML of the textarea, and the checked of the radio/checkbox. The less obvious ones are the selected and selectedIndex of the option, which are passively modified.
<input value="{this.state.value}"/>
When the input.value is taken from the component's state.value, when the user makes an input modification, and then JSX refreshes the view again, then the input.value takes the user's new value or the state's new value. value? Based on this disagreement, React gave a compromise solution that was supported by both, and today's topic was born.
React believes that value/checked cannot exist alone and needs to be used together with onInput/onChange/disabed/readOnly and other properties or events that control value/checked. Together they form a controlled component, which is controlled by JSX. If the user does not write these additional properties and events, the framework will add some events to it internally, such as onClick, onInput, and onChange, preventing you from inputting or selecting, and preventing you from modifying its value. Inside the framework, there is a stubborn variable, which I call persistValue, that keeps the value last assigned to it by JSX and can only be modified by internal events.
So we can assert that the controlled component can control the value through events.
In controlled components, persistValue can always be refreshed.
Let’s look at the uncontrolled components again. Since value/checked has been occupied, React enables another set of ignored attributes defaultValue/defaultChecked in HTML. It is generally believed that they are similar to value/checked, that is, when value does not exist, the value of defaultValue is regarded as value.
We have said above that the display of form elements is controlled by the internal persistValue, so defaultXXX will also synchronize persistValue, and then persistValue will synchronize the DOM. However, the starting point of uncontrolled components is to be loyal to user operations. If the user
input.value = "xxxx"
and later
<input defaultvalue="{this.state.value}"/>
in the code will no longer take effect, it will always be xxxx.
How does it do this, and how to identify whether the modification comes from inside or outside the framework? I looked through the source code of React, and it turns out that it has a thing called valueTracker to track the user's input
var tracker = { getValue: function () { return currentValue; }, setValue: function (value) { currentValue = '' + value; }, stopTracking: function () { detachTracker(node); delete node[valueField]; } }; return tracker; }
This thing is entered into the value/checked of the element through Object.defineProperty, so it knows the user Assign a value to it.
But value/checked are still two core attributes, involving too many internal mechanisms (such as value and oninput, onchange, input method events oncompositionstart,
compositionchange, oncompositionend, onpaste, oncut), in order to modify value/checked smoothly,
also needs to use Object.getOwnPropertyDescriptor. If I want to be compatible with IE8, there is no such advanced gadget. I take another safer way and
only use Object.defineProperty to modify defaultValue/defaultChecked.
First I add an _uncontrolled attribute to the element to indicate that I have hijacked defaultXXX. Then add another switch, _observing, in the set method describing the object (the third parameter of Object.defineProperty). When the view is updated inside the frame, this value is false. After the update, it is set to true.
This way you will know whether input.defaultValue = "xxx" was modified by the user or the framework.
if (!dom._uncontrolled) { dom._uncontrolled = true; inputMonitor.observe(dom, name); //重写defaultXXX的setter/getter } dom._observing = false;//此时是框架在修改视图,因此需要关闭开关 dom[name] = val; dom._observing = true;//打开开关,来监听用户的修改行为
The implementation of inputMonitor is as follows
export var inputMonitor = {}; var rcheck = /checked|radio/; var describe = { set: function(value) { var controllProp = rcheck.test(this.type) ? "checked" : "value"; if (this.type === "textarea") { this.innerHTML = value; } if (!this._observing) { if (!this._setValue) { //defaultXXX只会同步一次_persistValue var parsedValue = (this[controllProp] = value); this._persistValue = Array.isArray(value) ? value : parsedValue; this._setValue = true; } } else { //如果用户私下改变defaultValue,那么_setValue会被抺掉 this._setValue = value == null ? false : true; } this._defaultValue = value; }, get: function() { return this._defaultValue; }, configurable: true }; inputMonitor.observe = function(dom, name) { try { if ("_persistValue" in dom) { dom._setValue = true; } Object.defineProperty(dom, name, describe); } catch (e) {} };
I accidentally posted such a brain-burning code. This is a bad habit of coders. However, at this point, everyone understands that both official react and anu/qreact control user input through Object.defineProperty.
So we can understand the behavior of the following code
var a = ReactDOM.render(<textarea defaultValue="foo" />, container); ReactDOM.render(<textarea defaultValue="bar" />, container); ReactDOM.render(<textarea defaultValue="noise" />, container); expect(a.defaultValue).toBe("noise"); expect(a.value).toBe("foo"); expect(a.textContent).toBe("noise"); expect(a.innerHTML).toBe("noise");
Since the user has not manually modified the defaultValue, dom._setValue has always been false/undefined, so _persistValue can always be modified.
Another example:
var renderTextarea = function(component, container) { if (!container) { container = document.createElement("p"); } const node = ReactDOM.render(component, container); node.defaultValue = node.innerHTML.replace(/^\n/, ""); return node; }; const container = document.createElement("p"); //注意这个方法,用户在renderTextarea中手动改变了defaultValue,_setValue就变成true const node = renderTextarea(<textarea defaultValue="giraffe" />, container); expect(node.value).toBe("giraffe"); // _setValue后,gorilla就不能同步到_persistValue,因此还是giraffe renderTextarea(<textarea defaultValue="gorilla" />, container); // expect(node.value).toEqual("giraffe"); node.value = "cat"; // 这个又是什么回事了呢,因此非监控属性是在diffProps中批量处理的,在监控属性,则是在更后的方法中处理 // 检测到node.value !== _persistValue,于是重写 _persistValue = node.value,于是输出cat renderTextarea(<textarea defaultValue="monkey" />, container); expect(node.value).toEqual("cat");
Plain text class: text, textarea, JSX value, always converted to string
type="number" control, value It is always a number. If it is not filled in or is "", it will be converted to "0"
radio has a linkage effect. Only one radio control with the same name under the same parent node can be selected.
select's value/defaultValue supports arrays and does not perform conversion. However, if the user adds or deletes the underlying option elements, selected will change accordingly.
In addition, selection can be divided into fuzzy matching and exact matching.
//精确匹配 var dom = ReactDOM.render( <select value={222}> <option value={111}>aaa</option> <option value={"222"}>xxx</option> <option value={222}>bbb</option> <option value={333}>ccc</option> </select>, container ); expect(dom.options[2].selected).toBe(true);//选中第三个
//模糊匹配 var dom = ReactDOM.render( <select value={222}> <option value={111}>aaa</option> <option value={"222"}>xxx</option> <option value={333}>ccc</option> </select>, container ); expect(dom.options[2].selected).toBe(true);//选中第二个
凡此种种,React/anu都是做了大量工作,迷你如preact/react-lite之流则可能遇坑。
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
The above is the detailed content of A detailed introduction to controlled and uncontrolled components in React. For more information, please follow other related articles on the PHP Chinese website!

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version
Chinese version, very easy to use

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download
The most popular open source editor
