我在<table>
中附上<div>
。每当我们有更多的数据时,<div>
将有垂直滚动存在,在这种情况下,我想使表宽度为100%,如果不存在垂直滚动,我想使表宽度为98%。
render() {
return (
<div onScroll={this.handleScroll} className="scroll-property">
<table className="react-listing-table table" width={this.setWidth()+'%'}>
...
);
}
setWidth(){
let dom = ReactDOM.findDOMNode(this).parentNode;
let hasVerticalScrollbar = dom.scrollHeight > dom.clientHeight;
if (hasVerticalScrollbar) {
return 100;
} else {
return 98;
}
}
问题是我无法找到父domNode,即从表中查找div并获得运行时错误
typeError: Cannot read property 'parentNode' of null
请指导我
答案 0 :(得分:2)
When setWidth
is called inside the render
function, the DOM doesn't actually exist yet. This is something you want to do in componentDidMount
instead, and probably componentDidUpdate
as well, using a ref for the table.
tableRef = null
render() {
return (
<div onScroll={this.handleScroll} className="scroll-property">
<table className="react-listing-table table" ref={el => this.tableRef = el}>
...
);
}
componentDidMount() {
this.tableRef.width = this.setWidth() + '%'
}
componentDidUpdate() {
this.tableRef.width = this.setWidth() + '%'
}