React获取活动元素的Ref以获取getBoundingClientRect()。x

时间:2018-04-22 08:39:01

标签: javascript reactjs getboundingclientrect

您好我有一个关于如何从活动元素中获取React元素(名为 spanNav2 )的问题。以下示例完美无缺。我可以使用 getBoundingClientRect()。x 获取 x 值并移动span元素(见下文)。唯一的问题是 spanNav2 是固定的。我只是希望能够获得数字 2 并将其替换为注入的数字(值),就像我在导航元素中所做的那样。

    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>

在页面底部我有一个样式化的span元素,我想向左移动以位于活动元素下方(来自React Router的NavLink)

<span className={this.state.navigate} style={{ left: `${this.state.activeElement}px` }} />

有人能指出我正确的方向吗? 谢谢

1 个答案:

答案 0 :(得分:0)

假设create view employeespositions as select id as employee_id, primary_position_id as position_id from employees union all select id as employee_id, secondary_position_id as position_id from employees where secondary_position_id is not null; 是一个数字,那么你可以这样做:

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