1

您好,我有一个关于如何从活动元素中获取 React 元素(名为spanNav2 )的 Ref 的问题。下面的示例完美运行。我可以使用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` }} />

谁能指出我正确的方向?谢谢

4

1 回答 1

0

假设这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>
        )}
    )    
}
于 2018-04-22T09:36:37.573 回答