刚开始学习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>
你可以做这样的事情。
#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
中。