【发布时间】:2020-04-19 04:38:20
【问题描述】:
假设你有这个 JSX:
<div ref={this.divRef}>
<SomeComponent />
</div>
如果你想获取 ref 的名称并将其添加到你的状态,你会怎么做?
类似:
componentDidMount() {
// get all the positions of the current sections
if (this.divRef.current) {
this.setState({
breakpoints: [{
name: this.divRef.current.name,
position: this.divRef.current.getBoundingClientRect().bottom,
}],
}, () => {
// tslint:disable-next-line:no-console
console.log(this.divRef.current, 'this.divRef.current')
})
}
}
【问题讨论】:
-
引用没有名字。您是指 ref 所在的属性的名称吗?还是 ref 所指的 DOM 元素的
name属性? (div元素没有names,它们只有global attributes,name不是其中之一...)或标签名称(在您的示例中为"div")?跨度> -
如果它没有名字你想怎么得到它?您应该指定一个名称
-
对不起,我的问题不清楚。我想为每个 ref 分配一个名称,以便以后可以使用它
-
@A7DC 您需要在 this.divRef = React.createRef() 之类的构造函数部分声明引用构造函数,然后您可以使用 在页面上的任何位置使用该引用this.divRef.current
标签: javascript reactjs typescript ref