React:使用CSS类在数组中标记活动组件

时间:2015-02-26 21:49:35

标签: javascript reactjs

我正在将一系列句子加载到React中的数组句子中。在我的前端,我有一个“活动”句子,在用户表单输入后,加载数组中的下一个句子应该变为“活动”,并附加一个新的CSS类。

我该怎么做呢?我了解SentenceList需要跟踪active_sentence并且Sentence需要告知SentenceList已更新,并且当它发生时,应将“活动”类设置为下一句顺序。但我不确定如何实现它。

SentenceList

var SentenceList = React.createClass({
  render: function() {
    var sentences = [];
    active_sentence = 0;

    //loop through sentences and push each sentence into array
    this.props.sentences.forEach(function(sentence) {

      // increment an index variable here and put an if index === active_sentence statement?

      //grabs @sentences from Rails
      sentences.push(<Sentence key={sentence.id} details={sentence} />)
    });

    return (
      <div>{sentences}</div>
    )
  }
});

Sentence

var Sentence = React.createClass({
  getInitialState: function() {
    return {
      //
    }
  },

  addBlip: function(e) {
    var blipBody = this.refs.newBlip.getDOMNode().value;
    var sentenceId = this.props.details.id;
    var thisSentenceComponent = this;

    $.ajax({
      url: '/sentences/' + sentenceId + '/blips',
      type: 'POST',
      dataType: 'json',
      data: {blip: {body: blipBody}}
    });

    e.preventDefault();
  },

  render: function() {
    //get user input and submit blip and make next sentence "active"
    var phrase = this.props.details.body;
    var phrase_display = phrase.split("*");

    return (
      <div className="blipForm">
        {phrase_display[0]}
        {this.props.details.index}
        <form onSubmit={this.addBlip}>
          <input
            type="text"
            ref="newBlip"
          />
        </form>
        {phrase_display[1]}
      </div>
    )
  }
});

1 个答案:

答案 0 :(得分:0)

您可以在状态(此示例中为activeKey)中创建变量以跟踪哪个句子键被视为活动,然后可以将道具传递给Sentence,告诉它是否处于活动状态。下面的函数setActiveKey可用于在加载新句子时更新活动句子:

var SentenceList = React.createClass({
  getInitialState: function() {
    return {
      activeKey: false
    };
  },
  setActiveKey(newActiveKey){
    this.setState({activeKey: newActiveKey}); 
  },
  render: function() { 
    var sentences = [];
    this.props.sentences.forEach(function(sentence) {
      sentences.push(<Sentence isActive={this.state.activeKey === sentence.id} key={sentence.id} details={sentence} />)
    }.bind(this));
    return (
      <div>{sentences}</div>
    )}
});

然后在Sentence的渲染函数中,您可以使用道具isActive,如果值为true,则可以使用活动样式渲染它:

render: function() {  
  var phrase = this.props.details.body
  var phrase_display = phrase.split("*");

  return (
    <div className="blipForm" style={this.props.isActive ? styles.active : styles.inactive}>
      {phrase_display[0]}
      {this.props.details.index}
      <form onSubmit={this.addBlip}>
        <input type="text"
             ref="newBlip" />
      </form>
      {phrase_display[1]}
    </div>
  )
}

您可以在变量(styles此处)中控制样式:

var styles={
  active:{
    //set active styles here
  },
  inactive:{
    //set inactive styles here
  }
};