考虑下面给出的代码:
import Expo from 'expo';
import React from 'react';
import { StyleSheet, Text, View, Dimensions, StatusBar } from 'react-native';
import { Card, Button } from 'react-native-elements';
import Deck from './src/Deck';
import Item from './src/Item';
class App extends React.Component {
renderCard( item ) {
return (
<Item key={ item.id } imageUrl={ item.uri } />
);
}
renderNoMoreCards() {
return (
<Card title="All Done!">
<Text style={{ marginBottom: 10 }}>
There's no more content here!
</Text>
<Button
backgroundColor="#03A9F4"
title="Get more!"
/>
</Card>
);
}
render() {
return (
<View style={styles.container}>
<StatusBar hidden={true} />
<Deck
data={DATA}
renderCard={this.renderCard}
renderNoMoreCards={this.renderNoMoreCards}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff'
},
});
Expo.registerRootComponent(App);
我已经为 JavaScript 代码检查启用了 ESLint,但我得到了一个错误 Expected this to be used by class method renderNoMoreCards()。 (class-methods-use-this)
。
我知道错误是什么意思,但我如何创建方法来返回 jsx
?我可以将此方法创建为静态方法,但我们如何将静态方法作为 props 传递?
最佳答案
I can create this method as a static method, but how do we pass static methods as props?
通过引用它们,它们是构造函数的属性。因此,如果包含类是 App
,它将是 renderNoMoreCards={App.renderNoMoreCards}
:
static renderNoMoreCards() {
// ...
}
render() {
return (
<View style={styles.container}>
<StatusBar hidden={true} />
<Deck
renderNoMoreCards={App.renderNoMoreCards}
/>
</View>
);
}
另一个选项是一个独立的函数(大概是在一个模块中,所以它对那个模块是私有(private)的):
const renderNoMoreCards = _ =>
<Card title="All Done!">
<Text style={{ marginBottom: 10 }}>
There's no more content here!
</Text>
<Button
backgroundColor="#03A9F4"
title="Get more!"
/>
</Card>
;
class App extends React.Component {
renderCard( item ) {
return (
<Item key={ item.id } imageUrl={ item.uri } />
);
}
render() {
return (
<View style={styles.container}>
<StatusBar hidden={true} />
<Deck
data={DATA}
renderCard={this.renderCard}
renderNoMoreCards={renderNoMoreCards}
/>
</View>
);
}
}
关于javascript - 如何在没有 this 关键字的类中创建方法来返回组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43673389/