您好,我有一个问题,即如何从活动元素获取React元素的REF(名为 SPANNAV2 (。下面的示例正常工作。我能够使用 x 使用 getBoundingClientRect((。x 并移动跨度元素(见下文(。唯一的问题是 spannav2 是修复的。我只想能够获得数字 2 ,然后像我在 navigeation 元素中所做的那样,用注入数字(值(替换它。
onButtonClick = value => {
const open = !this.state.open;
const navigate = `cd-marker color-${value}`;
const activeElement = `${this.spanNav2.getBoundingClientRect().x}`;
const newState = {
open,
navigate,
activeElement
};
this.setState(newState);
if (open) {
setTimeout(() => this.setState({ animate: false }), 200);
}
};
在渲染元素中我有:
<li ref={input => {this.spanNav4 = input;}}>
<NavLinkPage2 onClick={value => this.onButtonClick(2)}>Content</NavLinkPage2</li>
,在页面的底部,我有一个样式的跨度元素,我想向左移动以坐在活动元素下方(React Router的NavLink(
<span className={this.state.navigate} style={{ left: `${this.state.activeElement}px` }} />
有人可以指向正确的方向吗?谢谢
假设value
是一个数字,那么您可以做这样的事情:
constructor(props) {
super(props)
this.refs = {}
onButtonClick = value => {
const open = !this.state.open;
const navigate = `cd-marker color-${value}`;
const activeElement = `${this.refs[value].getBoundingClientRect().x}`;
和render
功能内部,假设您再次在某些项目集合上进行map
:
render() {
return (
{this.props.items.map((item, index) => (
<li ref={input => {this.refs[index] = input}}>
<NavLinkPage2 onClick={value =>
this.onButtonClick(index)}>{item}</NavLinkPage2>
</li>
)}
)
}