【问题标题】:I am using the ref API usage correctly我正确使用了 ref API 用法
【发布时间】:2019-04-23 00:19:07
【问题描述】:

在一年不使用 React 后,现在回到 React,并注意到我们使用 Refs 的方式发生了一些变化。我已经多次阅读该部分关于我们应该如何使用回调并查看示例,但我仍然不能 100% 确定我在我的表单中正确使用了引用。

我已经阅读了文档和示例,但我的方式似乎既不适合旧方式也不适合新方式,所以有点难过。

[编辑] 为了清楚起见,我只是在处理表单上的提交并将其传递回另一个组件,但我想检查我在表单中处理 refs 的方式是否正常。抱歉,如果不清楚。

import React, { Component } from "react";
import { Card, Form, Button } from "react-bootstrap";

class LoginForm extends Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handelSubmit(e) {
    e.preventDefault();
    this.props.login(this.email.value, this.password.value);
  }

  render() {
    return (
      <Card>
        <Form className="m-4" onSubmit={this.handelSubmit}>
          <Form.Group controlId="formBasicEmail">
            <Form.Label>Email address</Form.Label>
            <Form.Control
              type="email"
              placeholder="Enter email"
              ref={input => {
                this.email = input;
              }}
            />
          </Form.Group>
          <Form.Group controlId="formBasicPassword">
            <Form.Label>Password</Form.Label>
            <Form.Control
              type="password"
              placeholder="Password"
              ref={input => {
                this.password = input;
              }}
            />
          </Form.Group>
          <Button variant="primary" type="submit" block>
            Login
          </Button>
        </Form>
      </Card>
    );
  }
}

export default LoginForm;
````


Can someone tell me if the way I am using the refs in my form are correct with current React Standards or how I should be doing it if wrong.

【问题讨论】:

  • 您尚未解释您发布的代码存在什么问题或提出了特定问题。请edit这样做。
  • 对不起,我想我很清楚我在问我对 refs 的实现是否正确
  • 本网站是针对与您在编程(代码)或使用程序员工具时遇到的问题相关的问题。您没有解释问题或提出问题(正如我之前提到的)。如果您只是想对您的工作代码进行同行评审,Code Review 就是为此特定目的而创建的。否则,您将需要具体说明问题并提出更具体的问题。
  • No issue Ken 有人向我提供了我想要的答案,我现在要自己研究原因。
  • 无论您是否得到答案,如果您不遵守网站指南,就会出现问题。

标签: reactjs react-ref


【解决方案1】:

如果您告诉我们您要做什么会有所帮助,但要回答您的问题,它应该如下所示:

// declare ref instance
emailRef = React.createRef();
passwordRef = React.createRef();

在您的表单控件上:

// email
ref={this.emailRef}
// password
ref={this.passwordRef}

// access your refs
var email = this.emailRef.current.value;
var password = this.passwordRef.current.value; 

【讨论】:

  • 我更新了我的问题以使其更清楚,你介意告诉我为什么这种方式比我目前的实现更好。或者我的如何不符合当前 React 实践的要求
  • 也感谢您给我一个真正有帮助的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-03
  • 2021-05-09
  • 2014-04-26
  • 2012-08-17
  • 1970-01-01
  • 2021-09-28
  • 1970-01-01
相关资源
最近更新 更多