【问题标题】:How to use innerRef in ReactStrap ? #TypeError: Cannot read property 'username' of undefined如何在 ReactStrap 中使用 innerRef ? #TypeError:无法读取未定义的属性“用户名”
【发布时间】:2020-08-24 21:48:30
【问题描述】:

我想从 Reactstrap 中的 innerRef 获取表单数据。但我收到 TypeError: Cannot read property 'username' of undefined

代码

            <FormGroup>
          <Label htmlFor="username"> Username</Label>
          <Input
            innerRef={(input) => (this.username.value = input)}
            type="text"
            name="username"
            id="username"
          />
        </FormGroup>

ErrorScreenshot

【问题讨论】:

  • 你的问题是this没有定义,所以设置username.value失败。最可能的原因是你有无状态的功能组件。尝试将其转换为类组件。为了帮助您更多,请发布您的组件的更多代码
  • 函数组件中如何使用Inner Ref?
  • 在功能组件内部更好地使用 useState - reactjs.org/docs/hooks-state.html 但我认为在你的情况下,你有错误的组件应该成为类,以便 this 可分配

标签: reactjs bootstrap-4 react-bootstrap reactstrap react-state


【解决方案1】:

你可以这样做; 对于无状态函数组件:

const Header = () => {
  let username: any;
  let password: any;
  let checkbox: any;

  const handleLogin = (event: any) => {
    console.log(
      "Username" +
        username?.value +
        "Password" +
        password?.value +
        "Checkbox" +
        checkbox?.value
    );
    event.preventDefault();
  };

  return (
    <Form onSubmit={handleLogin}>
      <FormGroup>
        <Label htmlFor="username">Username</Label>
        <Input
          type="text"
          id="username"
          name="username"
          innerRef={(x) => (username = x)}
        />
      </FormGroup>
      <FormGroup>
        <Label htmlFor="password">Password</Label>
        <Input
          type="password"
          id="password"
          name="password"
          innerRef={(x) => (password = x)}
        />
      </FormGroup>
      <FormGroup check>
        <Label>Remember</Label>
        <Input type="checkbox" name="remember" innerRef={(x) => (checkbox = x)} />
      </FormGroup>
      <Button className="bg-primary" type="submit" name="submit">
        Login
      </Button>
    </Form>
  );
};

【讨论】:

    猜你喜欢
    • 2019-07-27
    • 2016-05-08
    • 1970-01-01
    • 2021-08-03
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-11
    相关资源
    最近更新 更多