简体   繁体   English

如何使用 onPress() 渲染组件?

[英]How to render a component using onPress()?

I'd like to render / navigate to a new component passing props to it once I click on a button.一旦我点击一个按钮,我想渲染/导航到一个新的组件,将道具传递给它。

First attempt - syntax is wrong第一次尝试- 语法错误

{
  this.state.history ? (
    this.state.history.map(data => {
      return (
        <View style={styles.historyUnit}>
          <TouchableOpacity
          onPress={return <Map2 latitude={data1} longitude={data1} />;}
          >
            {" "}
          </TouchableOpacity>
        </View>
      );
    })
  ) : (
    <ActivityIndicator size="large" color="#0000ff" />
  );
}

Second attempt - component is not rendered第二次尝试- 组件未呈现

onPress={this.showHistory}
  showHistoryUnit = (data1, data2) => {
    return <Map2 latitude={data1} longitude={data1} />;
  };

Third attempt - I navigate to the component, but props are not passed第三次尝试- 我导航到组件,但没有传递道具

  showHistoryUnit = (data1, data2) => {
    this.props.navigation("map2")
    return <Map2 latitude={data1} longitude={data1} />;
  };

How can I make this happen?我怎样才能做到这一点?

this.state = {
    selectedId = 0
}

this.state.history.map(data => {
    return (
        <View style={styles.historyUnit}>
            <TouchableOpacity
                onPress={() => {
                    this.setState({ selectedId: data.id })
                }}
            >
                {data.id === this.state.selectedId &&
                    <Map2 latitude={data1} longitude={data1} />
                }
            </TouchableOpacity>
        </View>
    );
})

it just returns a Map2 component in the same time.它只是同时返回一个 Map2 组件。 if you want return Map2 in a row use array instead如果您想连续返回 Map2,请改用数组

Ideally, you should use a modal or similar for displaying specific Map information but this can also be achieved using component internal state.理想情况下,您应该使用模态或类似方式来显示特定的Map信息,但这也可以使用组件内部状态来实现。

state = {
    mapComponent: null,
};

if (this.state.history) {
    return this.state.mapComponent || this.state.history.map(data => {
        return (
            <View style={styles.historyUnit}>
                <TouchableOpacity
                    onPress={() => this.setState({ mapComponent: <Map2 latitude={data1} longitude={data1} /> })}
                >
                    {" "}
                </TouchableOpacity>
            </View >
        );
    })
}

return <ActivityIndicator size="large" color="#0000ff" />;

你可以使用带有 setState 的三元运算符就像当你在按钮中设置一些状态然后使用三元运算符来显示视图时this.state.history理想情况下检查你的this.state.history ,它应该是一个布尔值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM