Reactjs 如何减少React Native中的代码?
我想做的事 我现在的代码是这样的Reactjs 如何减少React Native中的代码?,reactjs,react-native,Reactjs,React Native,我想做的事 我现在的代码是这样的 从“React”导入React; 进口{ 容器、标题、正文、视图、内容、标题、文本、左、右 }来自“本土基地”; 导入“反应本机手势处理程序”; 从“app/src/Fire”导入火; 进口{ 样式表,图像,可触摸不透明度, }从“反应本机”; 导出默认类所有扩展React.Component{ 建造师(道具){ 超级(道具); 此.state={ 项目:[], }; } 异步组件didmount(){ const querySnapshot=wait Fire
从“React”导入React;
进口{
容器、标题、正文、视图、内容、标题、文本、左、右
}来自“本土基地”;
导入“反应本机手势处理程序”;
从“app/src/Fire”导入火;
进口{
样式表,图像,可触摸不透明度,
}从“反应本机”;
导出默认类所有扩展React.Component{
建造师(道具){
超级(道具);
此.state={
项目:[],
};
}
异步组件didmount(){
const querySnapshot=wait Fire.shared.getItems(1);
const items=wait Fire.shared.pushItems(querySnapshot);
this.setState({items});
}
render(){
const{items}=this.state;
返回(
{items.map((item)=>(
{item.name}
))}
);
}
}
我有另一个组件,它的代码与上面的几乎相同
区别在于类名和
wait Fire.shared.getItems(1);
或
wait Fire.shared.getItems(2);
我知道我应该将相同的代码组合成一个组件
如果您能给我任何建议或提示,我将不胜感激:)您可以提取此代码并在道具中传递数字1或2
import React from 'react';
import {
Container, Header, Body, View, Content, Title, Text, Left, Right
} from 'native-base';
import 'react-native-gesture-handler';
import Fire from 'app/src/Fire';
import {
StyleSheet, Image, TouchableOpacity,
} from 'react-native';
export default class All extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [],
};
}
async componentDidMount() {
const querySnapshot = await Fire.shared.getItems(this.props.nbrOfItems);
const items = await Fire.shared.pushItems(querySnapshot);
this.setState({ items });
}
render() {
const { items } = this.state;
return (
<Container>
<View>
{items.map((item) => (
<Image
source={{ uri: item.first_img_url }}
/>
<View>
<Text>{item.name}</Text>
</View>
))}
</View>
</Container>
);
}
}
从“React”导入React;
进口{
容器、标题、正文、视图、内容、标题、文本、左、右
}来自“本土基地”;
导入“反应本机手势处理程序”;
从“app/src/Fire”导入火;
进口{
样式表,图像,可触摸不透明度,
}从“反应本机”;
导出默认类所有扩展React.Component{
建造师(道具){
超级(道具);
此.state={
项目:[],
};
}
异步组件didmount(){
const querySnapshot=wait Fire.shared.getItems(this.props.nbrOfItems);
const items=wait Fire.shared.pushItems(querySnapshot);
this.setState({items});
}
render(){
const{items}=this.state;
返回(
{items.map((item)=>(
{item.name}
))}
);
}
}
您可以在任何类似这样的组件中调用此组件
<All nbrOfItems={1} />
或
<All nbrOfItems={2} />