我试图在反应组件中设置切换状态,但每次单击标题时页面都会向上滚动。我尝试将e.preventDefault添加到onClick函数,但它什么也没做。
我很确定它是由jsx元素的危险的SetInnerHTML部分引起的。
有没有办法阻止这种行为或者更好的方法呢?
this.props.page.acf.ios/android
是一个从WordPress JSON api返回的html字符串,返回如下内容(使用entities.decode转换任何html实体):
{
"ios": "<p><h1>How it works<\/h1><\/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><h1>Android stuff<\/h1><\/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;
答案 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.