【问题标题】:Conditional component rendering react native条件组件渲染反应原生
【发布时间】:2020-11-19 17:48:53
【问题描述】:

我正在尝试渲染条件组件。我有带有该位置的 MapView,我想要实现的是:如果该位置是从用户授予的或找不到该位置,而不是 MapView,我想呈现一个 Textinput,用户可以在其中手动键入他们的位置。这是我的代码

export default class GpsLocation extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      region: null,
    };
    this._getLocationAsync();
  }

  _getLocationAsync = async () => {
    let { status } = await Permissions.askAsync(Permissions.LOCATION);
    let location = await Location.getCurrentPositionAsync({
      enableHighAccuracy: true,
    });

    let region = {
      latitude: location.coords.latitude,
      longitude: location.coords.longitude,
      latitudeDelta: 0.0045,
      longitudeDelta: 0.0045,
    };
    this.setState({ region: region });
  };

  render() {
    if (this.status === "granted") {
      return (
        <View style={styles.locationContainer}>
        <Text style={styles.note}>Adresa</Text>
        <MapView
          initialRegion={this.state.region}
          showUserLocation={true}
          showCompass={true}
          rotateEnabled={false}
          style={{ flex: 1, borderRadius: 10 }}
        ></MapView>
      </View>
      );
    } else {
      return (
        <TextInput/>
      );
    }
  }
}

【问题讨论】:

  • 请说明您遇到的问题?

标签: reactjs react-native mobile


【解决方案1】:

试试这个方法

constructor(props) {
    super(props);
    this.state = {
      region: null,
      status : undefined, // add initially `undefined`
    };
    this._getLocationAsync();
  }

_getLocationAsync = async () => {
    let { status } = await Permissions.askAsync(Permissions.LOCATION);
    .......
    this.setState({ ... , status }); // update status here
  };

render() {
  // change here also
  return this.state.status === "granted" ? (
        <View style={styles.locationContainer}>
          <Text style={styles.note}>Adresa</Text>
          <MapView
            initialRegion={this.state.region}
            showUserLocation={true}
            showCompass={true}
            rotateEnabled={false}
            style={{ flex: 1, borderRadius: 10 }}
          ></MapView>
      </View>
      ) : <TextInput/> ;       
  }

【讨论】:

  • this.status 无法识别且未连接到 let { status } = await Permissions.askAsync(Permissions.LOCATION);
  • @ErmiraBKajtazi 欢迎 :-) 也请接受作为答案 :-)
  • 对不起,我测试了它并没有工作 this.status === "granted" 应该是别的东西,因为状态无法识别,你能帮我吗
  • 当我授予位置权限时,仍然只显示 TextInput,而不是 MapView
  • this.status改成this.state.status然后试试。我也更新了
猜你喜欢
  • 2017-06-24
  • 2020-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
相关资源
最近更新 更多