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} />;
}
}
};
Run Code Online (Sandbox Code Playgroud)
尝试使用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} />;
}
}
};
Run Code Online (Sandbox Code Playgroud)
使用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} />;
}
}
};
Run Code Online (Sandbox Code Playgroud)
先前的答案:
我设法获取对呈现的组件元素的引用的唯一方法是通过:
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>;
}
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5577 次 |
| 最近记录: |