在一个遗留项目中,我有React Bootstrap V3。
我需要将焦点移到下一个输入文本上。例如,如果用户已经将数字插入到第一输入中,则焦点需要在第二输入上。然后继续。
我知道我需要使用ref
,但我不明白如何使用多个参考。
这是我的代码:
export default class OtpInput extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
otp: "12",
};
}
componentDidUpdate() {
console.log("Update!");
console.log("this.inputControlRef ################", this.inputControlRef);
}
setOtp(e) {
// Only to invoke the componentDidUpdate()
this.setState({
otp: "21",
});
}
render() {
return (
<form className="otpInput">
<Row>
<Col xs={2}>
<FormGroup controlId="otpInput1">
<FormControl
inputRef={(ref) => {
this.inputControlRef = ref;
}}
type="text"
value={
this.state && this.state.otp.length > 0 && this.state.otp[0]
}
onChange={(e) => this.setOtp(e)}
/>
</FormGroup>
</Col>
<Col xs={2}>
<FormGroup controlId="otpInput2">
<FormControl
inputRef={(ref) => {
this.inputControlRef = ref;
}}
type="text"
value={
this.state && this.state.otp.length > 1 && this.state.otp[1]
}
onChange={(e) => this.setOtp(e)}
/>
</FormGroup>
</Col>
</Row>
</form>
);
}
}
对于inputControllerRef中的代码,我只有最后一个输入文本。
我试
<FormControl
inputRef={(ref) => {
this.inputControlRef[0] = ref;
}}
type="text"
value={
this.state && this.state.otp.length > 0 && this.state.otp[0]
}
onChange={(e) => this.setOtp(e)}
/>
但是我得到了Uncaught TypeError: Cannot set properties of undefined (setting '0')
2条答案
按热度按时间7cjasjjr1#
对于多个DOM引用,使用ref回调而不是ref对象。React公文- Ref回调
t5fffqht2#
在构造函数中定义类似的东西
添加您的组件如下所示
从这里进入第一个
以此为参考:https://codesandbox.io/s/gw6rp2?file=/App.js&utm_medium=sandpack