什么是React的参考?

时间:2017-10-19 00:00:38

标签: reactjs

我无法理解React中的refs。我知道它是一个回调函数,你把它放在渲染函数中,但除此之外,我无法理解它是什么以及它的目的是什么。

4 个答案:

答案 0 :(得分:9)

Refs是一种让你回过头来创建组件的方法。

<Text ref={(component)=>{this.textComponent = component}} > Here is some Text</Text>

然后在您的代码中,您可以通过执行以下操作来访问您的文本:

this.textComponent

这将使您能够以面向对象的方式调用组件上的函数。

我只想指出React / React-Native使用声明性编程范例,其中数据和“控制”通过自上而下的属性来管理。而在命令式样式中,您处理对象和指针并传递它们以便调用它们上的函数。在这种情况下,Refs是一个转义填充,它允许您获取声明的组件,以便您可以以命令式样式调用它们上的函数。

请参阅refs的官方React文档: https://reactjs.org/docs/refs-and-the-dom.html

答案 1 :(得分:3)

React有处理孩子的典型方式。它是以自上而下的方式使用props来实现的。要修改孩子,你必须用新道具重新渲染。但是在某些情况下,您希望在此典型流程之外修改/处理子项。在这些情况下,您使用refs。

Ref是一个接受回调的属性,每当安装或卸载组件时都会调用此回调。 Refs可以添加到dom元素或组件中。例如:

return (
  <div>
   <input
     type="text"
     // ref to a dom element
     ref={(input) => { this.textInput = input; }} />
  </div>
);

return (
  <MyComponent 
    // ref to a MyComponent(child component)
    ref={(component) => { this.childComponent = component; }}
    {...props}
  />
);

每当安装组件时,都会使用dom元素或子组件实例调用ref回调。每当卸载组件时,都会调用null

现在,您可以使用this.textInputthis.childComponent并在其上调用其不同的可用方法。

Refs只能提供给DOM元素或类组件。它们不适用于功能组件。例如:

function MyFunctionalComponent(props) {
  return <input type="text" />;
}

return (
  <MyFunctionalComponent 
    // This won't work
    ref={(component) => { this.childComponent = component; }}
    {...props}
  />
);

Refs只有在绝对必要时才能使用,因为它们可让您直接访问DOM中的元素/组件。

答案 2 :(得分:1)

引用是一个转义线,可让您直接访问DOM元素或组件实例。为了使用它们,您可以向组件添加ref属性,该组件的值是一个回调函数,该函数将接收基础DOM元素或组件的已安装实例作为其第一个参数。

class UnControlledForm extends Component {
  handleSubmit = () => {
    console.log("Input Value: ", this.input.value)
  }
  render () {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type='text'
          ref={(input) => this.input = input} />
        <button type='submit'>Submit</button>
      </form>
    )
  }
}

refs也可以通过利用JavaScript中的闭包与功能组件一起使用。

function CustomForm ({handleSubmit}) {
  let inputElement
  return (
    <form onSubmit={() => handleSubmit(inputElement.value)}>
      <input
        type='text'
        ref={(input) => inputElement = input} />
      <button type='submit'>Submit</button>
    </form>
  )
}

答案 3 :(得分:0)

引用是一种在DOM元素或类组件实例上设置变量的方法。

有两种类型的引用:回调引用和对象引用。

对象参考

对象引用是使用useRef()React.createRef()创建的。

要使用它们(带有引用DOM元素的功能组件的示例):

  1. 声明一个“容器”变量(将在下一步中指向DOM元素),并将其设置为等于useRef()。这是您的“参考对象”。

  2. 向您的DOM元素添加ref属性。将其设置为等于您的ref对象。

  3. 现在,这个ref对象代表您指向它的DOM元素,并且可以用来访问其方法和属性。

    function InputField() {
        const refForInput = useRef(); // 1. initializing `refForInput` as a reference object.
        return (
            <div>
                <input type='text' ref={refForInput} /> //2. passing it to the input element as its ref
                <button onClick={() => refForInput.current.focus()}>Click to focus the input field</button> // 3. now, calling `refForInput` will refer to the DOM <input> element, and you can access its `focus()` method.
            </div>
        )
    }
    

如果使用类组件,则过程类似;有关详细信息,请参见React docs

回调参考

回调引用的功能类似,但允许进行更细粒度的控制。

要创建一个回调引用,您可以类似地向DOM元素添加一个ref属性,但是您无需传递ref对象,而是传递一个回调。这个回调函数接收元素本身作为回调函数的参数。然后可以将其设置为等于现有值(类中的this.something;函数组件中已声明的变量。)

这里是Avid Programmer出色示例的带注释的版本;有关类的示例,请参见他的答案。

    function CustomForm({handleSubmit}) {
        let inputElement;
        return (
            <form onSubmit={() => handleSubmit(inputElement.value)}> // 2. Now, this refers to the `value` of the `<input>` element just below.
                <input
                type='text'
                ref={(input) => inputElement = input} // 1. so, here, `input` in the callback refers to the DOM element. Now, when the component mounts, `inputElement` will *reference* this DOM <input> element.
                />
                <button type='submit'>Submit</button>
            </form>
        )
    }

请注意,在卸载组件时,将使用null调用回调。

为什么有用?

它们不应该经常使用;它们的意思是逃生舱口。它们允许您访问在React组件上可能不可用的实际html元素上可用的API方法(focus()是一个常见示例)。如果这看起来令人困惑,请记住,例如,React按钮组件与html按钮组件不同。您可以在html按钮元素上调用focus(),但不能在React按钮元素上调用

相关问题