我有算法问题。我将Image uri从另一个组件发送到该组件。在touchableopacity中,我具有默认的img,但是当this.state.img不为null时,我想更改touchableopacity的图像。
这样的图片位置:
当我在这里发送图像时,我想填充第一位,如果我第二次发送,我希望它去第二位。这应该像这样。例如,前三个插槽已满,如果我删除第二个图像并再次发送图像到这里,我想填充第二个位置,因为第二个图像位置将是空闲的。 我该怎么办?。
render() {
return (
<View style={styles.container}>
<View style={{ width: '24%', height: '100%', justifyContent: 'center', alignItems: 'center', position: 'relative' }}>
<TouchableOpacity>
{
this.rend()
}
</TouchableOpacity>
</View>
<View style={{ width: '24%', height: '100%', justifyContent: 'center', alignItems: 'center', position: 'relative' }}>
<TouchableOpacity >
{
this.rend()
}
</TouchableOpacity>
</View>
<View style={{ width: '24%', height: '100%', justifyContent: 'center', alignItems: 'center', position: 'relative' }}>
<TouchableOpacity >
{
this.rend()
}
</TouchableOpacity>
</View>
)
}
这是方法:
rend() {
if (this.props.img === '')
{
return <View style={{ height: '100%', justifyContent: 'center', alignItems: 'center', aspectRatio: 1 }}>
<Image source={this.state.defaultImage} style={{ height: '90%', width: '90%' }} />
</View>
}
else
{
return <View style={{ height: '100%', justifyContent: 'center', alignItems: 'center', aspectRatio: 1 }}>
<Image source={{ uri: this.props.img }} style={{ height: '90%', width: '90%' }} />
</View>
}
}
答案 0 :(得分:1)
尝试一下:
const N_BUTTONS = 4;
const DEFAULT_IMG_URL = require('../Images/addcircle.png');
class YourComponent extends React.Component {
constructor(props) {
super(props);
// This create an empty array that you can map over:
const imgUrls = Array.apply(null, Array(N_BUTTONS));
this.state = {
imgUrls,
};
}
componentWillReceiveProps(nextProps) {
const { img: newImgUrl } = nextProps;
const { img: imgUrl } = this.props;
if (newImgUrl && newImgUrl !== imgUrl) {
const { imgUrls } = this.state;
// Take a copy to force refresh after setting state:
const imgUrlsClone = imgUrls.slice(0);
for (let i = 0; i < imgUrls.length; i += 1) {
if (!imgUrlsClone[i]) {
imgUrlsClone[i] = newImgUrl;
break;
}
}
this.setState({ imgUrls: imgUrlsClone });
}
}
removeImg = (imgIndex) => {
const { imgUrls } = this.state;
const imgUrlsClone = imgUrls.slice(0);
imgUrlsClone[imgIndex] = null;
this.setState({ imgUrls: imgUrlsClone });
};
renderContent = () => {
const { imgUrls } = this.state;
console.log('imgUrls', imgUrls.length);
return imgUrls.map((url, index) => {
// ex for url = require('../Images/image1.png')
const uri = url || DEFAULT_IMG_URL;
return (
<View key={index}>
<TouchableOpacity>
<Image source={uri} style={{ height: 50, width: 50 }} />
</TouchableOpacity>
</View>
);
});
};
render() {
return <View style={{ flex: 1 }}>{this.renderContent()}</View>;
}
}