【问题标题】:React.js refs not showing up inside objectReact.js refs 没有显示在对象内部
【发布时间】:2018-08-14 13:12:57
【问题描述】:
import { Button, Form, FormGroup, Label, Input, FormText } from 'reactstrap';

export default class UserPicForm extends React.Component {

  constructor() {
    super();

    // bindings
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
    event.preventDefault();
    let file = this;
    console.log('this is the file', file);
  }

  render() {
    return (
      <Form onSubmit={this.handleSubmit}>
        <FormGroup>
          <Label for="exampleFile">Upload Image</Label>
          <Input ref={(ref) => this.fileUpload = ref} type="file" name="file" id="exampleFile" />
          <FormText color="muted">
            Please use the field above to upload your profile picture. 
          </FormText>
        </FormGroup>

        <Button type="submit">Upload</Button>
      </Form>
    );
  }
}

我正在尝试上传一个文件并在表单提交时抓取它,我认为这是通过 ref 属性完成的,但是当我控制台记录我的“this”时,refs 属性为空。我做错了什么?

我还使用 React 检查器检查了我的 UserPicForm 组件,refs 部分也显示为“null”。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    Input 是来自reactstrap 的自定义元素。查看源代码,您似乎可以通过使用innerRef 来获取对其呈现的input 元素的引用。

    &lt;Input innerRef={(ref) =&gt; this.fileUpload = ref} /&gt;

    当在 HTML 元素上使用 ref 属性时,ref 回调 接收底层 DOM 元素作为其参数。

    See more information about refs here.

    【讨论】:

      【解决方案2】:

      不需要引用,event.target.elements.file 应该给出对输入的引用。

      如果你想以你设置的方式使用 ref,你的 ref 就是 this.fileUpload。

      如果您使用 ref=‘fileUpload’,则 refs 字段应该有一些内容。

      【讨论】:

        猜你喜欢
        • 2017-08-10
        • 2015-08-26
        • 1970-01-01
        • 2021-02-05
        • 2018-05-26
        • 1970-01-01
        • 1970-01-01
        • 2013-04-20
        • 1970-01-01
        相关资源
        最近更新 更多