简体   繁体   English

onPress不会在本机反应中检测到可触摸不透明的道具

[英]onPress doesn't detect props of touchable opacity in react native

onPress doesn't show me the id of my touchable opacity component when I press on it. 当我按onPress时,它不会显示可触摸的不透明度组件的ID。 He just shows me undefined. 他只是给我看不确定的东西。

    render() {
            var rows = [];
            var i = 0;
            while(i<5){
              rows.push(<TouchableOpacity id={i} activeOpacity={0.9} onPress={() => alert(this.props.id)}>
                  <View>
    </View>
                </TouchableOpacity>);
              i++;
            }
        return {rows}
}

I want to when I press on it, it shows the id of touchable opacity. 我要在按下它时显示可触摸的不透明度ID。 Please help me 请帮我

The component you have for this render() function would need to have a prop id for this to show an alert, but I think you are wanting to show each value of i . 您为此render()函数使用的组件将需要具有一个属性id才能显示警报,但是我认为您希望显示i每个值。 Due to i never going out of scope within this function (as it is var ), if you attempted to just do alert(i) it would show 5 for each button, but if you use const inside the while to store the current value of i , each button will have the correct value: 由于i永远不会超出此函数的范围(因为它是var ),如果您尝试只执行alert(i)则每个按钮将显示5 ,但是如果您在while内使用const来存储的当前值i ,每个按钮将具有正确的值:

while (i < 5) {
  const temp = i;

  rows.push(
    <TouchableOpacity
      id={i}
      activeOpacity={0.9}
      onPress={() => alert(temp)}
    >
      <View />
    </TouchableOpacity>,
  );

  i++;
}

You can't use a prop you are assigning in another prop you are assigning like you were trying to do. 您不能像要尝试的那样使用要分配的道具。

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

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