阅读this SO answer,我理解当我将函数传递给react组件时,我必须在构造函数中绑定一个函数,就像这样
constructor(props) {
super(props);
//binding function
this.renderRow = this.renderRow.bind(this);
this.callThisFunction = this.callThisFunction.bind(this);
}
或者我会收到这样的错误。
null不是对象:评估
this4.functionName
按照这个建议,我在构造函数中绑定了函数,但我仍然遇到同样的错误。
我正在使用React Native创建一个Master / Detail应用程序,该应用程序基于react native repo中的Movies示例,除了我不使用这种语法
var SearchScreen = React.createClass({
(这是回购的内容),而是这种ES6风格的语法
class ListOfLists extends Component {
在我的列表视图中,我会像这样渲染一行。
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}
}
关键是this.selectMovie(movie)
。当我单击带有电影名称的行时,我收到错误
null不是对象:
evaluating this4.selectMovie
问题:为什么告诉我null is not an object
或者为什么该函数为空?
更新
我在代码中添加了render方法,以显示renderRow
的使用位置
答案 0 :(得分:13)
在不修改代码的情况下处理此问题的方法很多
this.renderRow = this.renderRow.bind(this)
到您的类构造函数。
class New extends Component{
constructor(){
this.renderRow = this.renderRow.bind(this)
}
render(){...}
}
你添加了属性renderRow = { this.renderRow }
,实际上renderRow是用binded to null object执行的。尝试在this
中控制renderRow
,你会发现它是GlobalObject
而不是你想要的Class MovieList
。
答案 1 :(得分:1)
尝试使用es6语法:
selectMovie = (movie) => {
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,
});
}
}
然后
constructor(props) {
super(props);
this.selectMovie = this.selectMovie();
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
})
};
}
和
renderRow = (...) => {
return (
<ListCell
onSelect={this.selectMovie(movie)}
onHighlight={() => highlightRowFunc(sectionID, rowID)}
onUnhighlight={() => highlightRowFunc(null, null)}
movie={movie}
/>
);
}