Javascript React:使用CSS类标记数组中的活动组件
我正在将一系列句子加载到React中的句子数组中。在我的前端,我有一个活跃的句子,在用户表单输入之后,加载数组中的下一个句子应该变得活跃,并附加一个新的CSS类 我该怎么做呢?我知道SentenceList需要跟踪活动句子,句子需要告诉SentenceList已经更新,当它更新时,它应该按顺序将类活动设置为下一个句子。但我不知道如何实施它 句子表:Javascript React:使用CSS类标记数组中的活动组件,javascript,reactjs,Javascript,Reactjs,我正在将一系列句子加载到React中的句子数组中。在我的前端,我有一个活跃的句子,在用户表单输入之后,加载数组中的下一个句子应该变得活跃,并附加一个新的CSS类 我该怎么做呢?我知道SentenceList需要跟踪活动句子,句子需要告诉SentenceList已经更新,当它更新时,它应该按顺序将类活动设置为下一个句子。但我不知道如何实施它 句子表: 在本例中,您可以在状态activeKey中创建一个变量,以跟踪哪个句子键被认为是活动的,然后可以向句子传递一个道具,告诉它它是否是活动的。加载新句子
在本例中,您可以在状态activeKey中创建一个变量,以跟踪哪个句子键被认为是活动的,然后可以向句子传递一个道具,告诉它它是否是活动的。加载新句子时,可使用下面的函数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>
)}
});
您可以在变量样式中控制样式,如下所示:
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>
)
}
});
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>
)}
});
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>
)
}
var styles={
active:{
//set active styles here
},
inactive:{
//set inactive styles here
}
};