阅读
this SO answer,我明白当我将函数传递给react组件时,我必须像这样在构造函数中绑定一个函数
constructor(props) { super(props); //binding function this.renderRow = this.renderRow.bind(this); this.callThisFunction = this.callThisFunction.bind(this); }
或者我会得到这样的错误.
null is not an object: evaluating
this4.functionName
遵循该建议,我在构造函数中绑定了函数,但我仍然得到相同的错误.
我正在使用React Native制作一个Master / Detail应用程序,该应用程序基于react native repo中的Movies示例,但我不使用此语法
var SearchScreen = React.createClass({
(这是repo的意思)而是这个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(电影).当我单击带有电影名称的行时,出现错误
null is not an object:
evaluating this4.selectMovie
问题:为什么告诉我null不是一个对象,或者为什么该函数为null?
更新:
在不修改代码的情况下处理这个问题的方法很多
this.renderRow = this.renderRow.bind(this)到你的类构造函数.
原文链接:https://www.f2er.com/react/300908.htmlthis.renderRow = this.renderRow.bind(this)到你的类构造函数.
class New extends Component{ constructor(){ this.renderRow = this.renderRow.bind(this) } render(){...} }
你添加了属性renderRow = {this.renderRow},实际上用binded to null object执行了renderRow.尝试在renderRow中控制它,你会发现它是GlobalObject而不是你想要的Class MovieList.