gpt4 book ai didi

reactjs - 如何在高阶组件的上下文中获取对渲染元素的引用?

转载 作者:行者123 更新时间:2023-12-03 13:43:14 25 4
gpt4 key购买 nike

Foo 是包装 Bar 的高阶组件。我希望 Foo 获取对渲染的 Bar 元素的引用。

import React from 'react';

export default (Bar) => {
return class Foo extends React.Component {
componentDidMount = () => {
// How to obtain reference to the element that Bar renders to?
}

render() {
return <Bar {... this.props} />;
}
}
};

尝试使用 ref 获取对渲染元素的引用会解析为一个对象,该对象是 Bar 的实例,而不是元素本身:

import React from 'react';

export default (Bar) => {
return class Foo extends React.Component {
componentDidMount = () => {
console.log(this.refs.subject instanceof Bar);
}

render() {
return <Bar ref='subject' {... this.props} />;
}
}
};

最佳答案

使用findDOMNode:

我认为由于 this.refs.barBar 的实例,我可以使用 findDOMNode获取对渲染元素的引用。

import React from 'react';
import ReactDOM from 'react-dom';

export default (Bar) => {
return class Foo extends React.Component {
componentDidMount = () => {
console.log(ReactDOM.findDOMNode(this.refs.bar));
};

render() {
return <Bar ref='bar' {... this.props} />;
}
}
};

之前的回答:

我设法获取对渲染组件元素的引用的唯一方法是通过:

  1. Bar 包装在 ReactElement 中。
  2. 分配对 ReactElement 的引用。
  3. 迭代渲染的元素以获得其第一个子节点。
import React from 'react';

export default (Bar) => {
return class Foo extends React.Component {
componentDidMount = () => {
console.log(this.refs.bar.firstChild);
};

render() {
return <div ref='bar'>
<Bar {... this.props} />
</div>;
}
}
};

关于reactjs - 如何在高阶组件的上下文中获取对渲染元素的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32169065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com