0

我在我的 react-native 应用程序中有一个图像上传器,一旦您上传图像,它就会将您导航到另一个屏幕并在那里预览图像,在图像预览屏幕中,有一个用于为该图像命名的输入和一个保存按钮,单击保存按钮时,它应该返回上一个屏幕并在我拥有的平面列表中显示图像及其名称,我设法执行这些步骤,直到预览图像,但之后我不知道下一步该做什么,这是代码:

第一个画面:

  state = {
    image: null,
    previews: []
  };

  _pickImage = async () => {
    await Permissions.askAsync(Permissions.CAMERA_ROLL);
    const {navigate} = await this.props.navigation;

    let result = await ImagePicker.launchImageLibraryAsync({
      allowsEditing: false,
      aspect: [4, 4],
    });

    navigate( 'ImagePreview', { uri : result.uri } );

    if (!result.cancelled) {
      this.setState({ image: result.uri });
    }
  };

  _keyExtractor (item, index) {
      return index.toString();
    }

     _renderItem ({ item, index }) {
      return (
        <View>
        <Image source={require('')}/>
        <Text>Image title</Text>
        </View>
        );
    }

<FlatList style={{ flex: 0.5 }}
  data={this.state.previews}
  keyExtractor={this._keyExtractor.bind(this)}
  renderItem={this._renderItem.bind(this)}
  numColumns={2}
/>

第二屏:

const uri = navigation.getParam('uri');
<Image source={{uri:uri}} style={{width: 200, height: 200}} />
<Button title="Save" />
4

2 回答 2

1

据我了解,您正试图将数据从第二个屏幕发送回第一个屏幕。一种解决方案是在您传递到第二个屏幕的第一个屏幕内创建一个函数。

因此,您在第一个屏幕中声明一个函数,并在其中使用标题更新状态:

returnTitle(uri, title) {
    const {previews} = this.state;
    previews.push({uri, title});
    this.setState({previews});
}

当您导航到第二个屏幕时,您会传递此函数:

navigate('ImagePreview', { 
    uri: result.uri, 
    returnTitle: this.returnTitle.bind(this)
});

在您的第二个屏幕中,您为您的 Button 定义一个 onPress 处理程序,您可以在其中调用 returnTitle 函数并返回:

onSavePress = () => {
    const {title} = this.state; // Not sure where you store the title
    const {navigation} = this.props;
    const uri = navigation.getParam('uri');
    navigation.state.params.returnTitle(uri, title);
    navigation.goBack();
}

请记住从您的输入中获取标题。如果您将其存储在组件状态中,则代码不会显示。

现在在第一个组件中更改您的 _renderItem 方法以适应现在是对象数组的预览:

_renderItem ({ item, index }) {
    return (
        <View>
            <Image source={{uri: item.uri}}/>
            <Text>{item.title}</Text>
        </View>
    );
}
于 2018-12-11T21:58:41.060 回答
0

在您的第二个屏幕上,Image 标签应该有一个source属性,而不是image,如下所示:

<Image source={{uri:uri}} style={{width: 200, height: 200}} />

于 2018-12-11T21:14:06.950 回答