gpt4 book ai didi

react-native - 绑定(bind)传递给组件的函数

转载 作者:行者123 更新时间:2023-12-04 05:29:38 26 4
gpt4 key购买 nike

阅读 this SO answer ,我知道当我将一个函数传递给一个 react 组件时,我必须像这样在构造函数中绑定(bind)一个函数

 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



按照该建议,我在构造函数中绑定(bind)了该函数,但仍然遇到相同的错误。

我正在根据 react native repo 中的 Movies 示例使用 React Native 制作 Master/Detail 应用程序,但我不使用此语法
var SearchScreen = React.createClass({

(这就是 repo 的内容),而是这种 ES6 风格的语法
class ListOfLists extends Component {

在我的 ListView 中,我呈现这样的一行。
  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 is not an object: evaluating this4.selectMovie



问:为什么告诉我 null is not an object或者更确切地说,为什么该函数为空?

更新:

我在代码中添加了 render 方法以显示 renderRow 的位置习惯了

最佳答案

在不大量修改代码的情况下处理此问题的方法是添加this.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 .尝试控制台 thisrenderRow你会发现它是 GlobalObject而不是 Class MovieList你想要的。

关于react-native - 绑定(bind)传递给组件的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35446486/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com