【问题标题】:Coffeescript - React callback: sending child header click back to parentCoffeescript - React 回调:将子标题点击发送回父
【发布时间】:2015-05-14 18:06:06
【问题描述】:

刚开始学习 Coffeescript,我正在使用 React.js。我正在尝试确定哪个被点击,并且有人建议我不要在每个标题上使用数据属性。我有一些想法如何在 handleHeaderClick 函数下处理这个问题,但我不确定它们应该如何实现。我也在考虑将 ContactsTable 组件拆分为 ContactsTableHeader 组件和 ContactsTableRow 组件,但我在 ContactsTableHeader 中仍然应该有同样的问题 - 确定单击了哪个标题。

#Application.cjsx

handleHeaderClick: ->
   # childComponent.props
   # childComponent.refs
   # React.findDOMNode(childComponent.refs.firstName)
   # React.findDOMNode(childComponent.refs.lastName)
   # React.findDOMNode(childComponent.refs.age)

render: ->
  <div>
    <ContactsTable contactList={@state.contacts} onClick={@handleHeaderClick} />
  </div>



#ContactsTable.cjsx

render: ->
  if @props.contactList
    contactsList = @props.contactList.map (contact) ->
                <tr><td>{"#{contact.firstName}"}</td><td>{"#{contact.lastName}"}</td><td>{contact.age}</td></tr>


  <table style={tableStyle}>
    <thead style={headerStyle} onClick=@props.onClick>
        <tr>
            <th>FirstName</th>
            <th>Last Name</th>
            <th>Age</th>
        </tr>
    </thead>
    <tbody>
        {contactsList}
    </tbody>
  </table>

【问题讨论】:

  • 如果我错了,请纠正我。我假设您将单击“名字”、“姓氏”或“年龄”的th。你想捕捉哪个标题被点击了?
  • @DeepakPrasanna 没错!抱歉,我的描述第一行的标题标签被剪掉了。
  • 如果我的回答有帮助,您能告诉我吗?

标签: coffeescript reactjs


【解决方案1】:

你可以做这样的事情。

#Application.cjsx

handleHeaderClick: (header) ->
  @setState({clickedHeader: header})
  #do something else

render: ->
  <div>
    <ContactsTable contactList={@state.contacts} onClick={@handleHeaderClick} />
  </div>



#ContactsTable.cjsx

render: ->
  if @props.contactList
    contactsList = @props.contactList.map (contact) ->
                <tr><td>{"#{contact.firstName}"}</td><td>{"#{contact.lastName}"}</td><td>{contact.age}</td></tr>


  <table style={tableStyle}>
    <thead style={headerStyle}>
        <tr>
            <th onClick={@props.onClick('FirstName')}>FirstName</th>
            <th onClick={@props.onClick('LastName')}>Last Name</th>
            <th onClick={@props.onClick('Age')}>Age</th>
        </tr>
    </thead>
    <tbody>
        {contactsList}
    </tbody>
  </table>

这里 clickedHeader 保存在 Application.cjsx 中的组件中。您也可以将其保存在 ContactsTableHeader 中,看起来应该类似。

【讨论】:

    猜你喜欢
    • 2017-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多