代码之家  ›  专栏  ›  技术社区  ›  Aaron Balthaser

以id作为属性值响应ref

  •  1
  • Aaron Balthaser  · 技术社区  · 7 年前

    我有一个组件,正在尝试引用dom节点。我可以通过以下方式获取节点和子节点:

    export class AutoScrollTarget extends React.Component {
        constructor(props) {
            super(props);
    
            this.targetId = props.targetId;
        }
    
        componentDidMount() {
            console.log(this.refs.target);
        }
    
        render() {
            return (
                <div ref="target">
                    {this.props.children}
                </div>
            );
        }
    }
    

    问题是页面上会有许多组件,我希望引用值是“this.targetid”。

    我尝试了以下方法:

    render() {
        return (
            <div ref={this.targetId}>
                {this.props.children}
            </div>
        );
    }
    

    有没有一种简单而干净的方法来做到这一点?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Tholle    7 年前

    你可以用一个 ref callback ,这是一个函数,在装入元素时使用dom节点调用,并使用 null 当元素卸载时。

    例子

    render() {
        return (
            <div ref={ref => this.targetId = ref}>
                {this.props.children}
            </div>
        );
    }
    
    推荐文章