简体   繁体   English

ReactJS:如何使用setState旋转活动项

[英]ReactJS: how to use setState to swtich active item

Found mistake by myself, see my answer below 自己发现错误,请参见下面的答案

But I would appreciate, if smb explain me how this magic with handling events work. 但是,如果smb向我解释这种处理事件的神奇方式,我将不胜感激。 How changeActive function knows what index variable is? changeActive函数如何知道什么是索引变量?

I have list of statements, first of them is active by default. 我有语句列表,默认情况下它们首先处于活动状态。 I want to switch active on click. 我想点击激活。

The code below change Statements` component state activeIndex to the index of clicked statement. 下面的代码将Statements的组件状态activeIndex更改为clicked语句的索引。 But Statement component props active does not react as i assume, it's just disapear from every Statement, so there are no active items in my list. 但是激活状态的 Statement组件道具并没有像我想象的那样反应,只是从每个Statement中消失了,所以列表中没有活动的项。

So what's i've done wrong? 那我做错了什么? And what is a best practice? 最佳实践是什么?

statements.coffee statements.coffee

@Statements = React.createClass
  getInitialState: ->
    statements: @props.data.statements
    activeIndex: 0
  changeActive: (index) ->
    @setState activeIndex: index
    console.log(index)
  render: ->
    React.DOM.div
      className: 'row'
      React.DOM.div
        className: 'col-sm-9 statements'
        for statement, index in @state.statements
          React.createElement Statement, statement: statement, index: index, key: statement.id, active: (if @state.activeIndex == index then true), handleActiveStatement: @changeActive

statement.coffee statement.coffee

@Statement = React.createClass
  handleClick: ->
    @props.handleActiveStatement(index: @props.index)
  render: ->
    React.DOM.div
      className: 'statement ' + (if @props.active then 'active ' else null)
      onClick: @handleClick
      @props.index+1+'. '
      React.DOM.span null,
        @props.statement.body

OK, i found mistake. 好,我发现了错误。 May be it wiil be usefull for smb. 可能对smb有用。

Error is in this line: 错误在这一行:

@props.handleActiveStatement(index: @props.index)

It should be: 它应该是:

@props.handleActiveStatement(@props.index)

I would appreciate, if smb explain me how this magic with handling events work. 如果smb向我解释这种处理事件的神奇方式,我将不胜感激。 How changeActive function knows what index variable is? changeActive函数如何知道什么是索引变量?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM