【发布时间】:2015-07-06 22:44:42
【问题描述】:
我们现在在使用 react 时遇到了一些问题,但这有点归结为我们一直在使用 react 的一部分。
我们应该如何显示/隐藏子组件?
这就是我们的编码方式(这只是我们组件的 sn-ps)...
_click: function() {
if ($('#add-here').is(':empty'))
React.render(<Child />, $('#add-here')[0]);
else
React.unmountComponentAtNode($('#add-here')[0]);
},
render: function() {
return(
<div>
<div onClick={this._click}>Parent - click me to add child</div>
<div id="add-here"></div>
</div>
)
}
最近我一直在阅读一些例子,它应该是这样的:
getInitialState: function () {
return { showChild: false };
},
_click: function() {
this.setState({showChild: !this.state.showChild});
},
render: function() {
return(
<div>
<div onClick={this._click}>Parent - click me to add child</div>
{this.state.showChild ? <Child /> : null}
</div>
)
}
我应该一直使用那个 React.render() 吗?它似乎阻止了各种事情,比如shouldComponentUpdate 级联到孩子和e.stopPropagation 之类的事情......
【问题讨论】:
-
您能否更详细地解释您的第二个解决方案的问题是什么?这实际上是首选的方法。有一个状态属性
showChild,当你的div被点击时你会切换它。调用setState然后重新渲染你的组件。 -
@LarsBlumberg。哦。我实际上还没有使用第二种解决方案的经验。我只在一个小应用程序中尝试过,似乎可以工作。我们一直在使用第一个,因为它是以前教给我们的。但是现在我们遇到了诸如
stopPropagation不起作用或者我们需要在父级上触发shouldComponentUpdate时手动更新子级的问题。但是我还没有真正看到任何关于这种“首选方式”的文档,只有各种教程的示例。那么我们应该一直使用第二种解决方案吗? -
是的,第二个是更好的选择。 React 文档和示例不使用 JQuery。文档有很多很棒的信息。 facebook.github.io/react/docs/…
-
@WiredPrairie。好吧,我仍然可以使用
this.refs,我只是很快用 jQuery 编写了它。 -
根本不使用 jQuery,或者尽可能少地使用 jQuery。任何时候你操作 DOM,你都冒着 React 翻脸的风险。通常会吹出类似于:
unable to find component at root ''的错误