我将filterText=this.state.filterText
传递给子表,以仅过滤包含我在搜索器中键入的字母的电影。
在Table
组件内部,我创建了功能CheckIfFiltered
来过滤影片并检查表是否包含“ filterText”。
问题是,当我尝试运行它时,出现错误:
“未捕获的TypeError:无法读取未定义的属性'filterText'”
尽管我已经将filterText
传递给了props,但是传递给了Table组件。请帮我解决这个问题。
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')
);
最佳答案
将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() { ... }
})
关于javascript - 未捕获的TypeError:无法读取未定义的属性'filterText',我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34238835/