首页 > javascript > 如何编写if else内部渲染返回本机

如何编写if else内部渲染返回本机 (how to write if else inside render return react native)

问题

我想在if-else里面写render return。我想写,if ImageSource === null然后我想得到下面的代码。

    ImagePicker.showImagePicker(options, (response) => {
  console.log('Response = ', response);

  if (response.didCancel) {
    console.log('User cancelled photo picker');
  }
  else if (response.error) {
    console.log('ImagePicker Error: ', response.error);
  }
  else if (response.customButton) {
    console.log('User tapped custom button: ', response.customButton);
  }
  else {
    let source = { uri: response.uri };
    this.setState({
      ImageSource: source,
      data: response.data

    });
  }
});

这里是渲染返回

<TouchableOpacity onPress={this.selectPhotoTapped.bind(this)}>
      <View style={styles.ImageContainer}>
        {this.state.ImageSource === null ? <Text>Select a Photo</Text> :
          <Image style={styles.ImageContainer} source={this.state.ImageSource} />
        }
      </View>
    </TouchableOpacity>

否则我想获得上传的图像。

解决方法

使用undefined更新条件ImageSource条件。

<TouchableOpacity onPress={this.selectPhotoTapped.bind(this)}>
      <View style={styles.ImageContainer}>
        {this.state.ImageSource === undefined || this.state.ImageSouce === null ? <Text>Select a Photo</Text> :
          <Image style={styles.ImageContainer} source={this.state.ImageSource} />
        }
      </View>
    </TouchableOpacity>

问题

I want to write if-else inside render return. I want to write if ImageSource === null then I want to get the code below.

    ImagePicker.showImagePicker(options, (response) => {
  console.log('Response = ', response);

  if (response.didCancel) {
    console.log('User cancelled photo picker');
  }
  else if (response.error) {
    console.log('ImagePicker Error: ', response.error);
  }
  else if (response.customButton) {
    console.log('User tapped custom button: ', response.customButton);
  }
  else {
    let source = { uri: response.uri };
    this.setState({
      ImageSource: source,
      data: response.data

    });
  }
});

here is inside render return

<TouchableOpacity onPress={this.selectPhotoTapped.bind(this)}>
      <View style={styles.ImageContainer}>
        {this.state.ImageSource === null ? <Text>Select a Photo</Text> :
          <Image style={styles.ImageContainer} source={this.state.ImageSource} />
        }
      </View>
    </TouchableOpacity>

else I want to get the uploaded image.

解决方法

Update your condition ImageSource condition with undefined.

<TouchableOpacity onPress={this.selectPhotoTapped.bind(this)}>
      <View style={styles.ImageContainer}>
        {this.state.ImageSource === undefined || this.state.ImageSouce === null ? <Text>Select a Photo</Text> :
          <Image style={styles.ImageContainer} source={this.state.ImageSource} />
        }
      </View>
    </TouchableOpacity>
相似信息