动态创建没有字符串的引用

问题描述 投票:1回答:4

编辑:我们正在使用React 16.2.0,它与问题(see this answer)相关。

据我所知,这是创建ref的可接受方式(至少对于我们的反应版本):

<div ref={(r) => { this.theRef = r; }}>Hello!</div>

然后它可以使用这样的东西:

componentDidMount() {
  if (this.theRef) {
    window.addEventListener('scroll', this.handleScroll);
  }
}

这很好用。但是,如果我想创建一个动态命名的ref,比如说作为循环的一部分,我该如何命名ref?

现在提出过时的术语,我想要的是:

<div ref="{refName}">Hello!</div>

谢谢!

javascript reactjs
4个回答
1
投票

试试吧:

<div ref={refName}>Hello!</div>

1
投票

对于地图,您需要一个键,所以也许您可以使用该键映射到一个对象?像这样:

this.myRefs = {}

doSomethingToRef = (key) => {
  this.myRefs[key].doSomething()
}

return (
  myValues.map(value => (
    <div key={value.key} ref = {r => {this.myRefs[value.key] = r}}>{...}</div>
  ))
)

0
投票

像这样使用ref

在类构造函数中定义refName:

this.refName = React.createRef()

在元素中指定ref:

<div ref={this.refName} id="ref-name">Hello!</div>

要访问refName,请使用current:

this.refName.current

例:

if (this.refName.current.id == 'ref-name') {
  window.addEventListener('scroll', this.handleScroll);
}

更新

根据您的评论,要在旧版本中使用ref,您可以使用如下:

<div ref={(el) => this.refName = el} id="ref-name">Hello!</div>
{/* notice double quote is not used */}

要访问:

this.refs.refName

例:

if (this.refs.refName.id == 'ref-name') {
  window.addEventListener('scroll', this.handleScroll);
}

要以更好的方式做到这一点,你可以使用callback pattern


0
投票

[short-id][1]可能是一个很好的候选人!

它有如下方法:

ids.store('foo');  // "8dbd46"
ids.fetch('8dbd46');  // 'foo'
ids.fetch('8dbd46');  // undefined
ids.configure(Object conf)



$ npm install short-id

RefsCmp.js

var shortid = require('shortid');

const RefsList = (newrefs) = > (
   {newrefs.map(item => (
      <div ref={shortid.generate()}>Hello!</div>
   ))}
)

export default RefsList;
© www.soinside.com 2019 - 2024. All rights reserved.