在react中,受控组件(controlled components)是处理表单输入数据的推荐方式。它们通过将表单元素的值绑定到组件的state,并通过onchange事件处理器来更新这个state,从而使react成为“单一数据源”。然而,当受控组件的value属性直接绑定到一个频繁更新的外部状态(例如,父组件的datasource),并且onchange事件在每次按键时都触发这个外部状态的更新时,就可能导致输入框失去焦点。
其核心原因在于:
考虑以下原始代码片段:
// State to store DataSource in a parent component const [dataSource, setDataSource] = useState<any>(data); // Handler to update dataSource on every change const handleOnchange = (event: any, props: any) => { const newData = [...dataSource]; const itemIndex = newData.findIndex( (item) => item.OrderID === props.OrderID ); // Problematic line: Directly updates and sets the global dataSource on every keystroke newData[itemIndex].Freight = event.target.value; setDataSource(newData); }; // Custom Grid Component that renders an input const gridTemplate = (props: any) => { const val = props.Freight; // val directly comes from dataSource return ( <div> {/* Input value is tied to props.Freight, onChange updates dataSource */} <input value={val} onChange={(event) => handleOnchange(event, props)} /> </div> ); };
在这个例子中,gridTemplate组件接收props.Freight作为输入框的值。当用户在输入框中键入一个字符时,onChange事件触发handleOnchange函数。handleOnchange会立即更新dataSource状态,进而导致整个dataSource被重新设置。如果gridTemplate是作为列表项渲染的,那么dataSource的更新很可能导致整个列表或至少当前的gridTemplate组件重新渲染,从而使输入框失去焦点。
解决此问题的关键在于:让输入框自身管理其即时输入值,而仅在用户完成输入(例如,输入框失去焦点onBlur、按下回车键onKeyDown或点击保存按钮)时,才将最终值同步到外部的dataSource。
以下是具体的实现步骤和示例代码:
在输入框所在的组件(例如gridTemplate)内部维护局部状态: 使用useState钩子在gridTemplate组件内部声明一个状态,用于存储输入框的当前值。onChange事件将只更新这个局部状态,而不会立即触发表格或父组件的重渲染。
使用useEffect同步外部属性到内部状态(可选但推荐): 当gridTemplate组件的props.Freight(即来自dataSource的初始值或外部更新的值)发生变化时,useEffect可以确保内部的inputValue状态得到及时更新,从而保证数据的一致性。
在特定时机(如失焦或提交)更新外部数据源: 使用onBlur事件来监听输入框失去焦点的时机,或者使用onKeyDown事件监听特定的按键(如Enter键),此时才调用父组件传递下来的函数,将局部状态的最终值同步回dataSource。
以下是修改后的代码示例:
import React, { useState, useEffect, useCallback } from 'react'; // 假设这是您的父组件或数据源管理部分 const ParentComponent = () => { const [dataSource, setDataSource] = useState([ { OrderID: 1, Freight: 100.00 }, { OrderID: 2, Freight: 250.50 }, { OrderID: 3, Freight: 120.00 }, ]); // 这个函数现在只在输入框失焦或用户明确提交时调用 const updateDataSourceFreight = useCallback((orderId: number, newFreight: number) => { setDataSource(prevDataSource => { const newData = [...prevDataSource]; const itemIndex = newData.findIndex(item => item.OrderID === orderId); if (itemIndex > -1) { newData[itemIndex].Freight = newFreight; } return newData; }); }, []); // 依赖项为空数组,表示此函数在组件生命周期内是稳定的 // Custom Grid Component - 封装输入框逻辑 const GridTemplate = React.memo((props: any) => { // 使用局部状态管理输入框的即时值 const [inputValue, setInputValue] = useState(String(props.Freight)); // 确保初始值是字符串 // 当外部props.Freight变化时,更新内部inputValue useEffect(() => { setInputValue(String(props.Freight)); }, [props.Freight]); // 键入时只更新局部状态 const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => { setInputValue(event.target.value); }; // 失焦时才将最终值同步到外部数据源 const handleInputBlur = () => { // 确保转换成正确的类型,这里假设Freight是数字 const parsedValue = parseFloat(inputValue); if (!isNaN(parsedValue)) { props.onUpdateFreight(props.OrderID, parsedValue); } else { // 处理无效输入,例如恢复到原始值或给出提示 console.warn(`Invalid input for OrderID ${props.OrderID}: ${inputValue}. Reverting to original value.`); setInputValue(String(props.Freight)); // 恢复到上次有效值 } }; // 也可以在按下Enter键时触发更新 const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => { if (event.key === 'Enter') { const parsedValue = parseFloat(inputValue); if (!isNaN(parsedValue)) { props.onUpdateFreight(props.OrderID, parsedValue); event.currentTarget.blur(); // 触发失焦,以便键盘隐藏或焦点移开 } else { console.warn(`Invalid input for OrderID ${props.OrderID}: ${inputValue}. Reverting to original value.`); setInputValue(String(props.Freight)); } } }; return ( <div style={{ padding: '5px', border: '1px solid #eee', margin: '5px' }}> <span>Order ID: {props.OrderID} - Freight: </span> <input type="text" // 使用text以允许输入小数和负号,然后在onBlur/onKeyDown时解析 value={inputValue} onChange={handleInputChange} onBlur={handleInputBlur} onKeyDown={handleKeyDown} style={{ marginLeft: '5px' }} /> </div> ); }); return ( <div> <h3>Order List</h3> {dataSource.map(item => ( <GridTemplate key={item.OrderID} // 列表渲染必须提供唯一的key OrderID={item.OrderID} Freight={item.Freight} onUpdateFreight={updateDataSourceFreight} /> ))} <h4>Current Data Source:</h4> <pre class="brush:php;toolbar:false">{JSON.stringify(dataSource, null, 2)}
以上就是React输入框在键入字符后失去焦点:深入理解与解决方案的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号