我是React的新手,正在寻找一些最佳实践。我正在制作Chrome扩展程序,这是一个小小部件。小部件有3个部分。致电Section A
,Section B
和Section C
。在小部件的顶部,我希望有这样的按钮:
[logo] | Section A | Section B | Section C |
[
Panel Content (Default Section A)
]
当点击其中一个部分链接时,下面面板中的内容会更新该部分的相关内容。
我的第一个想法是渲染所有这些,然后隐藏jQuery show/hide()
在面板上。它可以工作,但我宁愿不这样做,因为每个面板异步加载一些数据,如果用户从不点击后两个链接,我宁愿不预先支付这个价格。
我为每个部分创建了React组件,因此很容易换出。
然后我尝试了这个:
showSectionB: function(){
React.renderComponent(
<SectionBList person={this.props.person} />,
document.querySelector('.main .panel')
);
},
render: function() {
return (
<div className="main">
<div className="actions">
<button className="T-I-ax7" onClick={this.showSectionB}>Section B</button>
</div>
<div className="panel">
<SectionAList person={this.props.person} />
</div>
</div>
);
}
感觉更合乎逻辑,但感觉很奇怪我到达容器中放置组件的组件内部。最重要的是,整个浏览器锁定并在面板切换后给我这条消息:
React attempted to use reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server.
还有更好的方法吗?
答案 0 :(得分:2)
React的关键是始终通过render()
呈现您的应用程序。用户交互应仅触发触发重新render()
的事件。在您的示例onClick
中,应调用setState()
来执行此操作。
getInitialState: function () {
return {
section: "a"
};
},
showSectionB: function(){
// Update the component's state for a re-render().
this.setState({
section: "b"
});
},
render: function() {
if (this.state.section == "a") {
var section = <SectionAList person={ this.props.person } />;
}
else if (this.state.section == "b") {
var section = <SectionBList person={ this.props.person } />;
}
return (
<div className="main">
<div className="actions">
<button className="T-I-ax7" onClick={ this.showSectionB }>Section B</button>
</div>
<div className="panel">
{ section }
</div>
</div>
);
}
已更新感谢您的评论!