【问题标题】:how to access property of React Native tag or element in onPress function?如何在 onPress 函数中访问 React Native 标签或元素的属性?
【发布时间】:2019-08-10 03:03:08
【问题描述】:

我想在 onPress 函数中访问 React Native 元素属性,我用 event.target 和 ReactNativeComponentTree 尝试过,但它不起作用,我想在 Onpress 函数中访问 audioPath 属性

  <Ionicons
  name="ios-play"
  size={35}
  color={this.state.playAudio ? "red" : "blue"}
  style={{
      left: 90,
      position: "relative",
      shadowColor: "#000",
      shadowOffset: { width: 0, height: 0 },
      shadowOpacity: 0.5,
      backgroundColor: "transparent"
  }}
  audioPath= {audioPath}
  onPress={this.audioPathFunction.bind(this)}
  />

【问题讨论】:

  • 请提及所有场景
  • 实际上我想渲染多个 ioniIcons 但问题是它们都具有相同的值我希望 ioniIcons 保持其自己的 audiopath 值,您要求的方法在我渲染时为所有 ioniIcons 赋予相同的值多次
  • 所以你有多个audioPath?
  • 是的,其实它是一个语音聊天应用,每个录音都有不同的路径,
  • 你有audioPath数组吗?

标签: javascript reactjs react-native


【解决方案1】:
 <Ionicons
  name="ios-play"
  size={35}
  color={this.state.playAudio ? "red" : "blue"}
  style={{
      left: 90,
      position: "relative",
      shadowColor: "#000",
      shadowOffset: { width: 0, height: 0 },
      shadowOpacity: 0.5,
      backgroundColor: "transparent"
  }}
  audioPath= {audioPath}
  onPress={()=> this.audioPathFunction(audioPath)}
  />

视情况而定。你可以在里面访问它,如果它的状态变量/类变量你可以在任何地方访问它,甚至在 onPress 函数中。如果它仅在 render() 中可用,则使用上面的指针函数(这不是一个好方法)

【讨论】:

  • 实际上我想渲染多个 ioniIcons 但问题是它们都具有相同的值我希望 ioniIcons 保持其自己的 audiopath 值,您要求的方法在我渲染时为所有 ioniIcons 赋予相同的值多次
【解决方案2】:

实际上我想渲染多个 ioniIcons 但问题是它们都具有相同的值

为此,您可以创建一个audioPath 数组并对其进行迭代以创建多个Ionicons 之类的,

conat audioPathArray = [audiopath1,audiopath2,audiopath3];

现在你可以遍历数组了,

{audioPathArray.map(audiopath=>{
  <Ionicons
    name="ios-play"
    size={35}
    color={this.state.playAudio ? "red" : "blue"}
    style={{
      left: 90,
      position: "relative",
      shadowColor: "#000",
      shadowOffset: { width: 0, height: 0 },
      shadowOpacity: 0.5,
      backgroundColor: "transparent"
    }}
    audioPath= {audioPath}
    onPress={()=> this.audioPathFunction(audioPath)}
   />
 })
}

这样你会得到和audioPath一样多的Ionicons,点击每个Ionicons会给你不同的audioPath

最后是你的函数,

audioPathFunction = (audioPath) => {
   console.log(audioPath)
}

【讨论】:

  • 没有任何方法可以访问 React 本机元素属性,因为您告诉的方法会使我的工作变得复杂,因为我的聊天包含音频和文本,就像在下面的示例中一样,我想获取 name 的值通过 onPress
  • @WaqarAmjad 如果要使用按钮,可以使用 touchableOpacity 将 OnPress 函数包裹在图标周围。
  • 那么你能用不同的audioPath渲染多个Ionicons吗?
  • @ravibagul91 使用 For Each 循环是的,我可以使用不同的 audioPath 渲染多个 Ionicons,但这不是我想要的输出,它使我的工作变得复杂,简单的事情告诉我,是否可以访问元素属性比如 event.target.value
  • 我认为不,这里是很好的信息来源 - github.com/facebook/react-native/issues/7892
猜你喜欢
  • 2021-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-15
相关资源
最近更新 更多