我有多个功能几乎相同。我该如何重构我的函数,以便不必编写多个函数。
这是我的代码:
renderImage = () => {
var imgSource = this.state.image? imageOne : imageTwo;
return (
<View style={{marginLeft:20, marginTop:20,width:50, height:67, backgroundColor:'transparent', alignItems:'center'}}>
<Image
style={{width:46, height:46}}
source={ imgSource }
/>
<Text style={{paddingTop:4, fontSize:11, color:'#4a4a4a'}}>some text</Text>
</View>
);
}
我还有另一个看起来很相似的功能:
renderImage2 = () => {
var imgSource = this.state.image2? imageThree : imageFour;
return (
<View style={{marginLeft:20, marginTop:20,width:50, height:67, backgroundColor:'transparent', alignItems:'center'}}>
<Image
style={{width:46, height:46}}
//I want to change source
source={ imgSource }
/>
//Also I want to change text
<Text style={{paddingTop:4, fontSize:11, color:'#4a4a4a'}}>some other text</Text>
</View>
);
}
我只想更改Image source
和text
。我可以这样做吗?
答案 0 :(得分:1)
创建另一个返回渲染但要传递2个道具的组件(源,文本)
import React from 'react';
import { Image, Text, View } from 'react-native';
class ImageWithText extends React.PureComponent {
render() {
const { source, text } = this.props;
return (
<View style={{ marginLeft: 20, marginTop: 20, width: 50, height: 67, backgroundColor: 'transparent', alignItems: 'center' }}>
<Image style={{ width: 46, height: 46 }} source={source} />
<Text style={{ paddingTop: 4, fontSize: 11, color: '#4a4a4a' }}>{text}</Text>
</View>
);
}
}
export default ImageWithText;
以及要使用新组件的时间
renderImage = () => {
var imgSource = this.state.image? imageOne : imageTwo;
return (
<ImageWithText source={imgSource} text="some text">
);
}
答案 1 :(得分:1)
您可以首先定义一个renderImage
函数,该函数需要一个参数来进行决策。在此renderImage
函数中,定义要在lookup
对象中加载的所有可能的图像,例如下面的
renderImage = (renderImage) => {
const lookup = {
image_1: { src: imageOne, text: 'text_for_image_one' },
image_2: { src: imageTwo, text: 'text_for_image_two' }
}
const selectedImage = lookup[renderImage] || undefined;
if(!selectedImage) return;
return (
<View style={{marginLeft:20, marginTop:20,width:50, height:67, backgroundColor:'transparent', alignItems:'center'}}>
<Image
style={{width:46, height:46}}
source={selectedImage.src}
/>
<Text style={{paddingTop:4, fontSize:11, color:'#4a4a4a'}}>{selectedImage.text}</Text>
</View>
);
}
然后在您的render
方法中执行以下操作
render() {
...
{this.renderImage(image_1)}
{this.renderImage(image_2)}
...
}
答案 2 :(得分:0)
您可以定义简单的函数渲染
renderImage = (imageSrc, text) => (
<View style={{marginLeft:20, marginTop:20,width:50, height:67, backgroundColor:'transparent', alignItems:'center'}}>
<Image
style={{width:46, height:46}}
//I want to change source
source={ imageSrc }
/>
//Also I want to change text
<Text style={{paddingTop:4, fontSize:11, color:'#4a4a4a'}}>{text}</Text>
</View>
)
最终用于渲染中,例如:
{this.renderImage(this.state.image? imageOne : imageTwo, 'some text')}