阅读这个SO答案,我明白当我将函数传递给react组件时,我必须在构造函数中绑定一个函数,就像这样
constructor(props) {
super(props);
//binding function
this.renderRow = this.renderRow.bind(this);
this.callThisFunction = this.callThisFunction.bind(this);
}
Run Code Online (Sandbox Code Playgroud)
或者我会得到这样的错误.
null不是对象:评估
this4.functionName
按照这个建议,我在构造函数中绑定了函数,但我仍然得到相同的错误.
我正在使用React Native制作一个Master/Detail应用程序,该应用程序基于react native repo中的Movies示例,但我不使用此语法
var SearchScreen = React.createClass({
Run Code Online (Sandbox Code Playgroud)
(这是回购的内容)而是这种ES6风格的语法
class ListOfLists extends Component {
Run Code Online (Sandbox Code Playgroud)
在我的列表视图中,我渲染这样的行.
class MovieList extends Component{
constructor(props){
super(props);
this.selectMovie = this.selectMovie.bind(this);
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
};
}
renderRow(
movie: Object,
sectionID: number | string,
rowID: number | string,
highlightRowFunc: (sectionID: ?number | string, rowID: ?number | string) => void,
) {
console.log(movie, "in render row", sectionID, rowID);
return (
<ListCell
onSelect={() => this.selectMovie(movie)}
onHighlight={() => highlightRowFunc(sectionID, rowID)}
onUnhighlight={() => highlightRowFunc(null, null)}
movie={movie}
/>
);
}
selectMovie(movie: Object) {
if (Platform.OS === 'ios') {
this.props.navigator.push({
title: movie.name,
component: TodoListScreen,
passProps: {movie},
});
} else {
dismissKeyboard();
this.props.navigator.push({
title: movie.title,
name: 'movie',
movie: movie,
});
}
}
render(){
var content = this.state.dataSource.getRowCount() === 0 ?
<NoMovies /> :
<ListView
ref="listview"
renderSeparator={this.renderSeparator}
dataSource={this.state.dataSource}
renderFooter={this.renderFooter}
renderRow={this.renderRow}
automaticallyAdjustContentInsets={false}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps={true}
showsVerticalScrollIndicator={false}
renderRow={this.renderRow}
}
Run Code Online (Sandbox Code Playgroud)
关键是this.selectMovie(movie)
.当我单击带有电影名称的行时,出现错误
null不是对象:
evaluating this4.selectMovie
问题:为什么它告诉我null is not an object
或者为什么该函数为null?
更新:
我在代码中添加了render方法,以显示renderRow
使用的位置
Obo*_*hin 15
在不修改代码的情况下处理此问题的方法是添加
this.renderRow = this.renderRow.bind(this)
到类构造函数中.
class New extends Component{
constructor(){
this.renderRow = this.renderRow.bind(this)
}
render(){...}
}
Run Code Online (Sandbox Code Playgroud)
你必须添加属性renderRow = { this.renderRow }
,实际上与执行renderRow 绑定到空的对象.尝试安慰this
中renderRow
,你会发现它是GlobalObject
代替Class MovieList
你的愿望.
归档时间: |
|
查看次数: |
20162 次 |
最近记录: |