在 reactjs 中输入 3 个值时如何自动聚焦美元值?
How to autofocus on the USD value when 3 values are entered in reactjs?
如上所述,当输入 3 个输入中的 1 个或全部 3 个时,如何设置关注我的美元值字段?
下面的代码当前显示来自 3 种不同类型字段的数据(收费金额、货币和 fysigned)
代码
https://codesandbox.io/s/8zv2v5mr22
谢谢
可以设置一个DOM Ref
用于美元值输入字段,然后用于控制对其的焦点。
在 App
组件的构造函数中,创建一个 Ref
字段。
constructor(props) {
//...
this.USDValueInputRef = React.createRef();
//...
}
对于 USDValue FormControl
,将 inputRef
属性设置为在 App
组件的构造函数中创建的 Ref
。
<FormControl
type="text"
defaultValue={this.state.USDValue}
inputRef={this.USDValueInputRef}
/>
检查前三个字段值是否设置的地方,可以关注USDValue输入,
if (/* condition */) this.USDValueInputRef.current.focus();
奖金:
您可以将状态更新从 onChangeAmountCharged
、handleChangeCurrency
和 handleChangeFYSigned
事件处理程序移动到 setUSDValue
。
onChangeAmountCharged(e) {
this.setUSDValue({ AmountCharged: e.target.value })
}
handleChangeCurrency(e) {
this.setUSDValue({ Currency: e.value })
}
handleChangeFYSigned(e) {
this.setUSDValue({ FYSigned: e.value })
}
然后在 setUSDValue
.
中一次性更新状态
setUSDValue(params) {
let currencyParams = { ...this.state, ...params };
const { AmountCharged, Currency, FYSigned } = currencyParams;
const completed = AmountCharged && Currency && FYSigned;
if (completed) {
currencyParams = {
...currencyParams,
USDValue: `${AmountCharged} ${Currency} ${FYSigned}`
};
}
this.setState(currencyParams, () => {
if (completed) this.USDValueInputRef.current.focus();
})
}
如上所述,当输入 3 个输入中的 1 个或全部 3 个时,如何设置关注我的美元值字段? 下面的代码当前显示来自 3 种不同类型字段的数据(收费金额、货币和 fysigned)
代码
https://codesandbox.io/s/8zv2v5mr22
谢谢
可以设置一个DOM Ref
用于美元值输入字段,然后用于控制对其的焦点。
在 App
组件的构造函数中,创建一个 Ref
字段。
constructor(props) {
//...
this.USDValueInputRef = React.createRef();
//...
}
对于 USDValue FormControl
,将 inputRef
属性设置为在 App
组件的构造函数中创建的 Ref
。
<FormControl
type="text"
defaultValue={this.state.USDValue}
inputRef={this.USDValueInputRef}
/>
检查前三个字段值是否设置的地方,可以关注USDValue输入,
if (/* condition */) this.USDValueInputRef.current.focus();
奖金:
您可以将状态更新从 onChangeAmountCharged
、handleChangeCurrency
和 handleChangeFYSigned
事件处理程序移动到 setUSDValue
。
onChangeAmountCharged(e) {
this.setUSDValue({ AmountCharged: e.target.value })
}
handleChangeCurrency(e) {
this.setUSDValue({ Currency: e.value })
}
handleChangeFYSigned(e) {
this.setUSDValue({ FYSigned: e.value })
}
然后在 setUSDValue
.
setUSDValue(params) {
let currencyParams = { ...this.state, ...params };
const { AmountCharged, Currency, FYSigned } = currencyParams;
const completed = AmountCharged && Currency && FYSigned;
if (completed) {
currencyParams = {
...currencyParams,
USDValue: `${AmountCharged} ${Currency} ${FYSigned}`
};
}
this.setState(currencyParams, () => {
if (completed) this.USDValueInputRef.current.focus();
})
}