这是父组件的一部分,在子组件呈现后获取元素之间的一些 px 测量值:
componentDidMount() {
// get the element where print area resides
let iframe = document.getElementById('ifmcontentstoprint').contentWindow.document.body;
// get the list of elements
let printArea = iframe.querySelectorAll('#printarea');
let positionTitle = iframe.querySelectorAll('#printarea .position-title, .position-title-print');
let pageFooter = iframe.querySelectorAll('#printarea tr.footer');
// total number of pages
var i = positionTitle.length;
// the position of the printarea within the the element
let printAreaPos = printArea[0].getBoundingClientRect().top
// iterate through the elements that are pairs
for (let i = 0; i <= positionTitle.length - 1; i++) {
console.log(pageFooter[i].getBoundingClientRect().top - positionTitle[i].getBoundingClientRect().top);
pageFooter[i].style.marginTop = '50px';
}
}
哪里pageFooter[i].style.marginTop = '50px';
是最终将以编程方式设置。出于测试目的,现在只使用静态数字。
这是应该添加样式的子组件的一部分:
<tr className='footer'>
<td id='hide'>
<div>
<div align='left' className='footer-columns'>
<p className='effective-date'>DATE EFFECTIVE: {this.props.effectiveDate}</p>
<p>© THE COMPANY</p>
<p>UNAUTHORIZED REPRODUCTION OR DISTRIBUTION PROHIBITED</p>
</div>
<div align='center' className='footer-columns middle-column'>
<p>{this.props.surveyName}</p>
<p>Page {i === 2 ? 1 : i === 5 ? 2 : i === this.props.totalCuts ? this.props.maxPages : null} of {this.props.maxPages}</p>
</div>
<div align='right' className='footer-columns'><img src={logo} alt='The Company Logo' /></div>
</div>
</td>
</tr>
我不明白为什么 pageFooter[i].style.marginTop = '50px';
没有被反射(reflect)出来,但是当我改变了 <tr className='footer' style={{ marginTop: '50px' }}>
它确实有效,即使它看起来呈现的是相同的 HTML。
所以我终于弄清楚了在 componentDidMount()
中所做的修改没有被添加回 DOM 的地方——它们基本上只是在内存中闲逛。
我应该如何将其发送回 DOM?
我最终希望能够做到pageFooter - positionTitle
位置比较,需要子组件先渲染才能获得测量值。
最佳答案
乍一看,我不明白为什么您编写的代码不起作用。我只是想提供另一种方法来看待这个问题,即让 React 控制元素本身的 marginTop。为此,我们必须使用组件的状态来存储所需的边距,然后按照您的指示使用 {{ marginTop: measurement }}
。以下是这种方法的可能概述:
class YourComponent extends React.Component {
constructor(props) {
super(props);
this.state = { margins: [] };
}
componentDidMount() {
// same as your previous code ...
const newMargins = [];
for (let i = 0; i <= positionTitle.length - 1; i++) {
newMargins.push('50px');
}
this.setState({ margins: newMargins });
}
render() {
const { margins } = this.state;
// and finally, you somehow make margins[index] reach your
// child component (the exact implementation depends on how
// your component is structured)
<tr className="footer" style={{ marginTop: margins[myIndex] }} />
}
}
关于javascript - 渲染后修改 React 组件中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52599782/