gpt4 book ai didi

javascript - react native : how to refactor a function

转载 作者:行者123 更新时间:2023-11-29 20:35:04 25 4
gpt4 key购买 nike

我有多个看起来几乎相同的函数。我怎样才能重构我的函数,这样我就不用写多个函数了。

这是我的代码:

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 sourcetext。我可以这样做吗?

最佳答案

创建另一个返回渲染但需要传入的 2 个 Prop (源、文本)的组件

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">
);
}

关于javascript - react native : how to refactor a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56944548/

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