React .CreateClass()滚动到参考:scrollintoview而不是函数



当我试图滚动到" ref"时,我很难弄清楚怎么了。我一直在疯狂搜索,发现URL完全有道理,但在我的情况下它不起作用。

  • https://github.com/yannickcr/eslint-plugin-react/issues/678
  • http://codepen.io/takatama/pen/mvvbqx

我有一个使用React 15.4.2以及React-Router 3.0.0的应用程序。我有一条通往选项的组件的路由,该组件采用可选路由参数,并试图使用它滚动到componentDidupdate()上的元素。我已经尝试实施几种不同的方法,但是在遵循Ref.Scrollintoview()的最新实现时,我会遇到一个错误...

scrollintoview不是函数

我确保在componentDidupdate()。

我只是缺少使用.createclass()时缺少您在使用类定义时会得到的方法,或者我正在接近这完全错误?

我可以跳到使用软件包,但是这样的事情是无法理解我可能打扰我的本地时发生的事情。

代码已被简化以在保持类似流程的同时展示问题。代码语法中可能存在差异。

应用

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>
        )
    }
});

主页只是一个带有导航栏的包装纸,该包装可以根据主动索引

来渲染儿童

添加新项目是将获得/页面/[新创建的项目索引的组件]

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>
        );
    }
});

带有ref的嵌套反应组件只是那个,而不是带有dom元素方法的dom元素,因此元素方法将无法可用。

要轻松修复,您可以将React组件包装在标准DOM元素中并为此分配。

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>
        )
    });
},

接受的答案中的概念对于来自UI框架的元素(例如ReactStrap,Smantic UI,Material UI等)特别是正确的。

当他们拥有相同名称时,这很容易被遗忘。

<Input>或React -Strap中的<Form>不是<input><form>

这样的带有ref的组件是"不是Dom元素方法的dom元素",如被接受的答案所示。

最新更新