如何使用React.createRef()API从Class Component ref获取DOM节点

hor*_*gen 8 reactjs react-dom

我有这两个组成部分:

import { findDOMNode } from 'react-dom';

class Items extends Component {
    constructor(props) {
        super(props);
        this.ref = React.createRef();
        this.selectedItemRef = React.createRef();
    }

    componentDidMount() {
        if (this.props.selectedItem) {
            this.scrollToItem();
        }
    }

    componentWillReceiveProps(nextProps) {
        if (this.props.selectedItem !== nextProps.selectedItem) {
            this.scrollToItem();
        }
    }

    scrollToItem() {
        const itemsRef = this.ref.current;
        const itemRef = findDOMNode(this.selectedItemRef.current);

        // Do scroll stuff here
    }

    render() {
        return (
            <div ref={this.ref}>
                {this.props.items.map((item, index) => {
                    const itemProps = {
                        onClick: () => this.props.setSelectedItem(item.id)
                    };

                    if (item.id === this.props.selectedItem) {
                        itemProps.ref = this.selectedItemRef;
                    }

                    return <Item {...itemProps} />;
                })}
            </div>
        );
    }
}

Items.propTypes = {
    items: PropTypes.array,
    selectedItem: PropTypes.number,
    setSelectedItem: PropTypes.func
};
Run Code Online (Sandbox Code Playgroud)

class Item extends Component {
    render() {
        return (
            <div onClick={() => this.props.onClick()}>item</div>
        );
    }
}

Item.propTypes = {
    onClick: PropTypes.func
};
Run Code Online (Sandbox Code Playgroud)

this.selectedItemRef在Items :: scrollToItem()中获取DOM节点的正确方法是什么?

阵营的文档不鼓励使用findDOMNode(),但有没有其他办法?我应该在Item中创建ref吗?如果是这样,我如何访问Items :: componentDidMount()中的ref?

谢谢

Ros*_*son 2

我认为你想要的是current例如this.selectedItemRef.current

\n\n

它记录在本页的示例中:\n https://reactjs.org/docs/refs-and-the-dom.html

\n\n

在此输入图像描述

\n\n

为了安全起见,我还在 js 小提琴上尝试了它,它按预期工作了!https://jsfiddle.net/n5u2wwjg/195724/

\n\n

如果你想获取 React 组件的 DOM 节点,我认为处理这个问题的首选方法是让子组件来完成繁重的工作。因此,如果您想调用focus组件内部的输入,例如,您\xe2\x80\x99d 让组件设置引用并调用组件上的方法,例如

\n\n

this.myComponentRef.focusInput()

\n\n

然后 componentRef 将有一个被调用的方法focusInput,然后调用focus输入。

\n\n

如果您不想这样做,那么您可以使用 findDOMNode 进行修改,我想这就是不鼓励这样做的原因!

\n\n

(编辑是因为我在回答后意识到你已经了解current并想了解反应组件。对此非常抱歉!)

\n