React dangerouslySetInnerHTML导致页面滚动到顶部

时间:2015-07-28 21:14:46

标签: javascript html wordpress reactjs

我试图在反应组件中设置切换状态,但每次单击标题时页面都会向上滚动。我尝试将e.preventDefault添加到onClick函数,但它什么也没做。

我很确定它是由jsx元素的危险的SetInnerHTML部分引起的。

有没有办法阻止这种行为或者更好的方法呢?

this.props.page.acf.ios/android是一个从WordPress JSON api返回的html字符串,返回如下内容(使用entities.decode转换任何html实体):

{
    "ios": "<p>&lt;h1&gt;How it works&lt;\/h1&gt;<\/p>\n<p>Navigation menus are reached from the header by tapping an associated menu icon.<\/p>\n<p>When a user clicks on the hamburger icon in the header, the main navigation menu opens.<\/p>\n<p>The main menu can appear in several states:<\/p>\n<ul>\n<li>Logged Out<\/li>\n<li>Logged In<\/li>\n<\/ul>\n<p>Navigation menu items are displayed with title casing.<\/p>\n<p><img class=\"alignnone size-full wp-image-89\" src=\"http:\/\/mobilestyle.ups.dev\/wp-content\/uploads\/2015\/07\/logged-out.jpg\" alt=\"logged-out\" width=\"292\" height=\"519\" \/><\/p>\n"
}, {
    "android": "<p>&lt;h1&gt;Android stuff&lt;\/h1&gt;<\/p>\n<p><img class=\"alignnone size-full wp-image-89\" src=\"http:\/\/mobilestyle.ups.dev\/wp-content\/uploads\/2015\/07\/logged-out.jpg\" alt=\"logged-out\" width=\"292\" height=\"519\" \/><\/p>\n"
}

以下是相关组件:

let MobileTabs = React.createClass({
  getInitialState() {
    return {
      togglePage: false
    }
  },

  handleClick(e) {
    e.preventDefault();
    this.setState({
      togglePage: !this.state.togglePage
    })
  },

  render() {
    let acf = this.props.page.acf;

    if (this.state.togglePage) {
      return <div className="page__mobile_tabs">
               <h2 onClick={this.handleClick}>Android</h2>

               <div dangerouslySetInnerHTML={{__html: entities.decode(acf.android)}}></div>
             </div>;

    } else {
      return <div className="page__mobile_tabs">
               <h2 onClick={this.handleClick}>iOS</h2>

               <div dangerouslySetInnerHTML={{__html: entities.decode(acf.ios)}}></div>
             </div>;
    }
  }
});

module.exports = MobileTabs;

2 个答案:

答案 0 :(得分:0)

您是否尝试将return函数的render数据包装在parens中?

否则javascript将隐含地在行的末尾插入分号

答案 1 :(得分:0)

It is possible that the scroll is being caused by the dom elements being removed and then added back in. If you add key property that lets React know to re-use the dom element instead of removing and adding a new element. In this case, you'd want to use the same key in both the Android and ios cases.

return <div key="mobile_tabs" className="page__mobile_tabs">

If adding key doesn't work, all try adding a min-height in page__mobile_tabs and see if that helps prevent the scroll. For testing, you could use a large height, like 1500px.