reactjs - 反应:从按钮更改字段的值
问题描述
我有这个相当简单的应用程序,它有多个输入,并且只有当前字段的状态和当前字段的输入。当您单击输入时,它会相应地设置“当前字段”和“当前输入”,而不是在模糊时重置。
有没有办法实现一个按钮来重置当前字段的值,如下所示?
import React, { useState } from 'react'
const FieldTest = () => {
const [currentField, setCurrentField] = useState(1)
const [currentInput, setCurrentInput] = useState('A')
const fields = [...Array(4)].map((current, i) => (
<input
key={i}
type='text'
onFocus={e => {
setCurrentField(i + 1)
setCurrentInput(e.target.value)
}}
onChange={e => setCurrentInput(e.target.value)}
defaultValue={String.fromCharCode(64 + i + 1)}
/>
))
return (
<>
<h1>Field Test</h1>
<p>Current Field: {currentField}</p>
<p>Current Input: {currentInput}</p>
{fields}
<button
onClick={e => {
/*Is there any way to implement this by only changing this onClick?*/
}}
>
Reset Current Field's Input
</button>
</>
)
}
export default FieldTest
这可以通过将其重构为每个输入的状态或每个输入的 ref 来轻松实现,但如果有任何方法我无法实现(因为它使添加可变数量的输入变得容易得多),请告诉我。
或者,如果有一种完全不同的方法来实现这一点,也允许可变数量的输入,请告诉我!
谢谢!
解决方案
您可以使用 keep one ref 并.current
根据所关注的元素更改其值。
import React, { useState, useRef } from "react";
export default function App() {
const [currentField, setCurrentField] = useState(1);
const [currentInput, setCurrentInput] = useState('A');
const curInputRef = useRef(null);
const fields = [...Array(4)].map((current, i) => {
return (
<input
key={i}
type="text"
onFocus={(e) => {
setCurrentField(i + 1);
setCurrentInput(e.target.value);
curInputRef.current = e.target; //make the ref point to the focused input
}}
onChange={(e) => setCurrentInput(e.target.value)}
defaultValue={String.fromCharCode(64 + i + 1)}
/>
);
});
return (
<>
<h1>Field Test</h1>
<p>Current Field: {currentField}</p>
<p>Current Input: {currentInput}</p>
{fields}
<button
onClick={(e) => {
if (!curInputRef.current) return;
curInputRef.current.value = ''; //change the value of the focused input to be ''
/*Is there any way to implement this by only changing this onClick?*/
}}
>
Reset Current Field's Input
</button>
</>
);
}
运行中的脚本: https ://codesandbox.io/s/admiring-saha-2uo2f?file=/src/App.js
推荐阅读
- javascript - 使用 javascript 更改 liferay-ui:input-localized XML
- c++ - CPP,创建数组,我只看到一个参数
- rust - 如何关闭宏观卫生?
- python - 在字符串中查找匹配的左/右大括号索引
- c# - Telerik Kendo grid for jquery does not show data
- python - Django 在 HttpResponse 中返回图像和数据
- php - MySQL TRUNCATE & INSERT 长时间运行
- python - 如何在python中将元组列表转换为固定键目录格式
- linux - Linux 脚本失败
- android - 非法类文件:类模块信息缺少超类型。com.google.code.gson\gson\2.8.6