I recently started working with ReactJS
. Specifically, I am utilizing the react-rails
ruby gem and react-bootstrap
components.
I have a question regarding placing onClick
event listeners in child components.
As you can see from the code sample below, I have a parent component that 'calls' a child component in its render
function. Within that render
function, I have React onClick
listener that calls handleToggle
when it is clicked.
###* @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>`
Unfortunately, this doesn't work the way I thought it would. ToggleIconButton::handleToggle
never gets called. Instead, the onClick
listener is placed on IconButton
and references ToggleIconButton::handleToggle
.
I don't want to add any additional behavior to IconButton
. The way I see it, no conditional logic should be placed in IconButton
. All it should do is represent an icon and button and not have to worry about any browser events. That's what ToggleIconButton
is for.
While I know I could wrap a React Div
around IconButton
and write an onClick
listener there (I've tried this and it works), it seems like that's a bit janky.
Does anybody know a good way of doing this? Thanks guys!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…