我将filterText=this.state.filterText
传递给子表,仅过滤包含我在搜索者中输入的字母的影片。
在Table
内部组件中我创建了函数CheckIfFiltered
来过滤电影并检查表格是否包含" filterText"。
问题是,当我尝试运行它时会出现错误:
"未捕获的TypeError:无法读取属性' filterText'未定义"
虽然我已将filterText
传递给道具,但仍传递给桌面组件。请帮我解决这个问题。
var Row = React.createClass({
render: function(){
return(
<tr>
<td>{this.props.episode.title}</td>
<td><a href ="top">Link</a></td>
</tr>
);
}
});
var Table = React.createClass({
render: function(){
var CheckIfFiltered=function (episode, index, ar){
if (episode.title.toLowerCase().indexOf(this.props.filterText.toLowerCase()) > -1){
return true;
}
else {
return false;
}
}
var filter_rows = this.props.episodes.filter(CheckIfFiltered).map(function(episode){
return <Row episode={episode} key={episode.title} /> ;
});
return(
<div className="row spacer">
<div className="col-lg-4 col-lg-offset-4">
<table width="100%">
<tbody>{filter_rows}</tbody>
</table>
</div>
</div>
);
}
});
var Search = React.createClass({
changeFilteringSearch: function(){
this.props.changeFiltering(
this.refs.filterTextInput.value
);
},
render: function(){
return (
<div className="row ">
<div className="col-lg-4 col-lg-offset-4">
<input type="search" className="form-control" value = {this.props.filterText} ref="filterTextInput" onChange={this.changeFilteringSearch} className="form-control" placeholder="Search for episode" />
</div>
</div>
);
}
});
var FilterableEpisodesTable = React.createClass({
getInitialState: function() {
return {
filterText: 'qwerty'
};
},
changeFiltering: function(text){
this.setState({
filterText: text
});
},
render: function(){
return(
episodes=this.props.episodes,
<div>
<Search filterText={this.state.filterText} changeFiltering={this.changeFiltering}/>
<hr/>
<Table episodes={episodes} filterText={this.state.filterText}/>
</div>
);
}
});
var episodes = [{title : "Angular with Yeoman",},
{title : "Using D3 with Rickshaw and Angular",},
{title : "Canvas with paper.js",},
{title : "Express.js middleware",},
{title : "Metro",}
];
ReactDOM.render(
<FilterableEpisodesTable episodes = {episodes}/>,
document.getElementById('example')
);
&#13;
答案 0 :(得分:1)
CheckIfFiltered
在您将其传递给过滤器时在不同的上下文中运行,因此它只需要绑定。
要么
var CheckIfFiltered=function( episode ){
if (episode.title.toLowerCase().indexOf(this.props.filterText.toLowerCase()) > -1){
return true;
} else {
return false;
}
}.bind( this )
或
var filter_rows = this.props.episodes.filter(CheckIfFiltered.bind( this )).map( ... )
应该可以帮助您正确地确定范围。或者将它添加为类方法,我认为React.createClass
自动绑定函数但请注意,如果您更改为ES2015语法,则会发生从不自动绑定的JS本机行为,因此您必须自己绑定它。
React.createClass({
CheckIfFiltered: function( episode, index, ar ){
return episode.title.toLowerCase().indexOf(this.props.filterText.toLowerCase()) > -1 ? true : false
},
render: function() { ... }
})
答案 1 :(得分:0)
我认为这是一个简单的范围问题,请检查一下,如果有帮助请告诉我。
render: function(){
var self = this;
var CheckIfFiltered=function (episode, index, ar){
if (episode.title.toLowerCase().indexOf(self.props.filterText.toLowerCase()) > -1){
return true;
}
else{
return false;
}