我仍在尝试理解react.js中的状态概念。有谁可以帮助下面的jsfiddle?我正在尝试根据所选类别过滤记录。
var App = React.createClass({
render: function() {
return (
<div>
<Instructions />
<h1>Requests</h1>
</div>
);
}
});
答案 0 :(得分:1)
从我发现的反应中,在不具有父子关系的组件之间进行通信变更需要在作为两者的父级的顶级组件中管理状态。尝试通信的组件。在您的示例中,App
是您的顶级组件,其中包含MySelect
和DisplayRecords
作为子级。如果您希望MySelect
的状态影响DisplayRecords
中显示的行,则您必须在App
状态下对其进行管理。
在示例中,我移动了选择框&#39;选择App
状态,并相应地将道具传递给不同的组件。我尽力用评论来解释显着的变化,但如果您对任何更改有疑问,请务必发表评论!
var DisplayRecords = React.createClass({
render: function(){
var _this = this; // avoid conflicting this keyword
return (
<div>
<table><tbody> // include tbody to avoid errors (weird react thing)
{_this.props.records.map(function(record){ // loop through each record
// if all records is selected, or the record status matches the selection
if(_this.props.filter=="All Requests" || record.status == _this.props.filter){
// return the record as a table row
return (
<tr key={record.id} >
<td>{record.title}</td>
<td><a href="#">{record.status}</a></td>
<td>{record.updated_at}</td>
<td>{record.created_at}</td>
<td><a href="#">Delete</a></td>
</tr>
)
}
})}
</tbody></table>
</div>
)
}
});
var MySelect = React.createClass({
callParentFunction: function(e) {
// call parent's getFilter function with the selected option's text as argument
this.props.changeHandler(e.target.options[e.target.selectedIndex].text);
},
render: function() {
// note removed specified value of select box
return (
React.createElement("select", { onChange: this.callParentFunction},
React.createElement("option", { value: 1 }, "All Requests"),
React.createElement("option", { value: 2 }, "Approved"),
React.createElement("option", { value: 3 }, "Denied"),
React.createElement("option", { value: 4 }, "Pending")
)
)
}
});
var App = React.createClass({
getInitialState: function(){
// set initial selection
return {
selected: "All Requests"
}
},
getFilter:function(newFilter){
// set new selection on change of select box
this.setState({selected: newFilter})
},
render: function() {
// pass selected state to both MySelect and DisplayRecords
// pass getFilter to MySelect so it can be called onChange
return (
<div>
<MySelect selection={this.state.selected} changeHandler={this.getFilter} />
<h1>Requests</h1>
<DisplayRecords records={this.props.data} filter={this.state.selected} />
</div>
);
}
});
React.render(<App data={requests}/>, document.getElementById('container'));