React .createClass()滚动到ref:scrollIntoView不是函数

Jef*_*eff 4 javascript dom reactjs react-router

当我试图滚动到"参考"时,我无法弄清楚出了什么问题.我一直在疯狂地搜索并找到了完全合理的网址,但它在我的场景中无效.

我有一个使用react 15.4.2以及react-router 3.0.0的应用程序.我有一个路由到一个组件,该组件采用可选的路由参数,并尝试使用它来滚动到componentDidUpdate()上的元素.我尝试了几种不同的方法,但在遵循ref.scrollIntoView()的最新实现时,我收到错误...

scrollIntoView不是一个函数

我确保在componentDidUpdate()时存在"ref回调".

我只是缺少像使用.createClass()这样的东西,你在使用类定义时遇到的方法是缺少的还是我接近这个完全错误的方法?

我可以跳到使用一个包,但是这样的事情是无法理解当我像我一样可以打扰我的时候发生了什么.

代码已经过简化,以便在保持类似流程的同时展示问题.代码语法可能存在差异.

APP

const App = React.createClass({
    render() {
        return (
            <Router history={ appHistory }>
                <Route path='home' component={ Home }>
                    <IndexRoute component={ Page } />
                    <Route path='page(/:itemIndex)' component={ Page } />
                </Route>
                <Route path='add-new-item' component={ AddNewItem } />
            </Router>
        )
    }
});
Run Code Online (Sandbox Code Playgroud)

HOME 只是一个包含导航栏的包装器,可以根据活动索引呈现子项

添加新项目 是一个组件,它将转到/页面/ [新创建的项目的索引]

const Page = React.createClass({
    getInitialState() {
        return {
            data: undefined,
            scrollTo: parseInt(this.props.params.goalIndex) || undefined
        };
    },

    componentWillMount() {
        // this gets data and does a setState for data
    },

    componentDidUpdate() {
        let { scrollTo } = this.state;

        if( scrollTo && this['item-' + scrollTo] ) {
            this['item-' + scrollTo].scrollIntoView();
        }
    },

    renderTiles() {
        return this.state.data.map( ( item, index ) => {
            return (
                <Item
                    key={ 'item-' + index }
                    ref={ node => this['item-' + index] = node }
                >
                    <p>foo bar...</p>
                </Item>
            )
        });
    },

    render() {
        return (
            <div>
                { this.state.data && this.renderTiles() }
            </div>
        );
    }
});
Run Code Online (Sandbox Code Playgroud)

Jef*_*eff 17

带有ref的嵌套React组件就是那个而不是具有DOM元素方法的DOM元素,因此Element方法将不可用.

要轻松修复,可以将React组件包装在标准DOM元素中并为其指定ref.

renderTiles() {
    return this.state.data.map( ( item, index ) => {
        return (
            <div
                key={ 'item-' + index }
                ref={ node => this['item-' + index] = node }
            >
                <Item>
                    <p>foo bar...</p>
                </Item>
            </div>
        )
    });
},
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢。这并不明显,我一直在用头撞墙,直到找到这个答案。 (2认同)