【问题标题】:What is difference between ref and key in reactjs?reactjs中的ref和key有什么区别?
【发布时间】:2017-08-31 11:11:52
【问题描述】:

ref和Key都是用来指向元素的,但是这两者的基本区别是什么?

【问题讨论】:

  • 简而言之 ref 是供我们使用的,key 将用于 react 内部使用。
  • ref 提供对 DOM 元素的访问权限。而key 标识已更改、添加或删除的项目。 facebook.github.io/react/docs/lists-and-keys.html
  • 查看这两个单独的答案以获取有关这两个refkeys 的更多详细信息

标签: reactjs key ref


【解决方案1】:

按键

Keys React 用于识别已更改的特定虚拟 DOM 元素。使用键的经典示例是列表。假设我们有一个对象数组:

fruits = [{name: "Pineapple", id: 1}, {name: "Banana", id: 2}, {name: "Passion Fruit", id: 3}

如果我们将此数组作为 prop 传递给 FruitList 组件,以便在页面上呈现水果列表,我们将遍历水果数组,将每个水果呈现为列表项:

const FruitList = (props) =>{
  const fruits = props.fruits.map((fruit) =>
    <li>{fruit.name}</li>
  )
  return(
    <ul>
      {fruits}
    </ul>
  )
}

您可能还会发现自己处于数组中的项目实际上并不具有唯一 ID 的情况。如果渲染项没有稳定的 ID,可以使用迭代器的索引作为键。

const FruitList = (props) =>{
  const fruits = props.fruits.map((fruit, index) =>
    <li key={index}>{fruit.name}</li>
  )
  return(
    <ul>
      {fruits}
    </ul>
  )
}

参考文献

类似于键 refs 以属性的形式添加到元素中。根据 React.js 文档,使用 refs 的一些最佳案例是:管理焦点、文本选择或媒体播放、触发动画以及与第三方 DOM 库集成。

通常 props 是父组件与其子组件交互的方式。但是,在某些情况下,您可能需要修改子节点而不使用新道具重新渲染它。这正是使用 refs 属性的时候。

过去,字符串和回调函数都被允许作为值传递给 refs,但是现在字符串被认为是遗留的,并且可能在未来的某个时候被弃用。在将 ref 属性传递给 HTML 元素时,我们将这个 DOM 元素作为参数传递给回调函数:

class TextInput extends React.Component {
  constructor(props) {
    super(props);
    this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusInput() {
    this.textInput.focus();
  }

  render() {
    return (
      <div>
        <input
          type="text"
          ref={(input) => { this.textInput = input }} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focusInput}
        />
      </div>
    );
  }
}

来源:https://medium.com/@nothingisfunny/keys-and-refs-in-react-fd954457fd75

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 2019-10-26
    • 2013-09-22
    相关资源
    最近更新 更多