作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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.bar
是 Bar
的实例,我可以使用 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} />;
}
}
};
之前的回答:
我设法获取对渲染组件元素的引用的唯一方法是通过:
Bar
包装在 ReactElement
中。ReactElement
的引用。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/
我是一名优秀的程序员,十分优秀!