javascript 如何使用多个引用在输入之间移动焦点?

kuuvgm7e  于 12个月前  发布在  Java
关注(0)|答案(2)|浏览(87)

在一个遗留项目中,我有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')

7cjasjjr

7cjasjjr1#

对于多个DOM引用,使用ref回调而不是ref对象。React公文- Ref回调

t5fffqht

t5fffqht2#

  • 基于类的组件 *

在构造函数中定义类似的东西

constructor() {
  super();
  this.formControl = [];
}

添加您的组件如下所示

<FormControl
  inputRef={(el) => this.formControl[0] = el}
  type="text"
  value={this.state && this.state.otp.length > 0 && this.state.otp[0]}
  onChange={(e) => this.setOtp(e)}
/>
<FormControl
  inputRef={(el) => this.formControl[1] = el}
  type="text"
  value={this.state && this.state.otp.length > 1 && this.state.otp[1]}
  onChange={(e) => this.setOtp(e)}
/>

从这里进入第一个

componentDidUpdate() {
  console.log("Update!");
  console.log("First Form Control", this.formControl[0]);
}

以此为参考:https://codesandbox.io/s/gw6rp2?file=/App.js&utm_medium=sandpack

相关问题