【发布时间】:2014-07-28 23:27:55
【问题描述】:
我最近开始使用ReactJS。具体来说,我正在使用react-rails ruby gem 和react-bootstrap 组件。
我有一个关于在子组件中放置onClick 事件侦听器的问题。
从下面的代码示例中可以看出,我有一个父组件,它在其render 函数中“调用”一个子组件。在 render 函数中,我有 React onClick 监听器,当它被点击时会调用 handleToggle。
###* @jsx React.DOM ###
ToggleIconButton = React.createClass
getInitialState: ->
toggleOn: false
handleToggle: (evt) ->
this.setState(toggleOn: !this.state.toggleOn)
render: ->
`<IconButton onClick={this.handleToggle}>Toggle Button</IconButton>`
IconButton = React.createClass
render: ->
# BsButton and BsGlyphicon are React-Bootstrap components
`<BsButton>
<BsGlyphicon glyph={this.props.glyph} />
{" " + this.props.text}
</BsButton>`
不幸的是,这并没有像我想象的那样工作。 ToggleIconButton::handleToggle 永远不会被调用。相反,onClick 侦听器放置在IconButton 上并引用ToggleIconButton::handleToggle。
我不想向IconButton 添加任何其他行为。在我看来,没有条件逻辑应该放在IconButton 中。它应该做的只是代表一个图标和按钮,而不必担心任何浏览器事件。这就是ToggleIconButton 的用途。
虽然我知道我可以在 IconButton 周围包裹一个 React Div 并在那里写一个 onClick 监听器(我已经尝试过并且它有效),但这似乎有点笨拙。
有人知道这样做的好方法吗?谢谢大家!
【问题讨论】:
-
<ActualJSXChildComponents />的细微差别使得the answers here 值得一读