


Detailed explanation of React controlled components and uncontrolled components
This article mainly explains to you in detail the controlled components and uncontrolled components of React. There is not much information about controlled components and uncontrolled components on the official website and domestic websites. Some people think that they are available or not, and they 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, but there are a large number of reports in the background system, different forms are linked, and there is a lack of controlled components. Really can not.
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 value of input, innerHTML of textarea, checked of radio/checkbox, not so much. The obvious ones are selected and selectedIndex of option, which are passively modified.
<input>
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, at this time, 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 controlled components, which are 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 is the control of value that can be completed through event.
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>
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 The assignment operation to its value.
But value/checked are still two very core attributes, involving too many internal mechanisms (for example, value and oninput, onchange, input method events oncompositionstart,
compositionchange, oncompositionend, onpaste, oncut), In order to modify value/checked smoothly,
also use Object.getOwnPropertyDescriptor
. If I want to be compatible with IE8, there is no such advanced gadget. I take another safer way,
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 a switch, _observing
, to the set method of the description 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.
f (!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 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></textarea>, container); ReactDOM.render(<textarea></textarea>, container); ReactDOM.render(<textarea></textarea>, 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></textarea>, container); expect(node.value).toBe("giraffe"); // _setValue后,gorilla就不能同步到_persistValue,因此还是giraffe renderTextarea(<textarea></textarea>, container); // expect(node.value).toEqual("giraffe"); node.value = "cat"; // 这个又是什么回事了呢,因此非监控属性是在diffProps中批量处理的,在监控属性,则是在更后的方法中处理 // 检测到node.value !== _persistValue,于是重写 _persistValue = node.value,于是输出cat renderTextarea(<textarea></textarea>, container); expect(node.value).toEqual("cat");
Of course, there are many types of form elements, and each form element also has its default behavior.
纯文本类:text, textarea, JSX的值,总是往字符串转换
type="number"的控制,值总是为数字,不填或为“”则转换为“0”
radio有联动效果,同一父节点下的相同name的radio控制只能选择一个。
select的value/defaultValue支持数组,不做转换,但用户对底下的option元素做增删操作,selected会跟着变动。
此外select还有模糊匹配与精确匹配之分。
//精确匹配 var dom = ReactDOM.render( <select> <option>aaa</option> <option>xxx</option> <option>bbb</option> <option>ccc</option> </select>, container ); expect(dom.options[2].selected).toBe(true);//选中第三个
//模糊匹配 var dom = ReactDOM.render( <select> <option>aaa</option> <option>xxx</option> <option>ccc</option> </select>, container ); expect(dom.options[2].selected).toBe(true);//选中第二个
凡此种种,React/anu都是做了大量工作,迷你如preact/react-lite之流则可能遇坑。
相关推荐:
The above is the detailed content of Detailed explanation of React controlled components and uncontrolled components. For more information, please follow other related articles on the PHP Chinese website!

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.