首页 > 解决方案 > 如何在反应原生元素按钮中使用 TouchableComponent 道具?

问题描述

backgroundColor:我试图在已设置为的 RNE 按钮内实现涟漪效果,'transparent'因为它位于图像之上。我正在尝试实现该Ripple('grey', false)方法,TouchableNativeFeedback以使用透明以外的其他颜色来实现此效果。我在 RNE Button 文档中读到它接受一个我认为(希望)我可以调用该方法并指示它使用的颜色的TouchableComponent道具。但是我没有在互联网上找到任何关于如何做到这一点的示例,我也无法想象使用它应该遵循的语法......我希望在解决这个问题时不影响 IOS 默认可触摸不透明度的解决方案,即在这种情况下,一个确实可以正常工作。请检查我基于自己的文档的链接:[Ripple()https://react-native-elements.github.io/react-native-elements/docs/button.html#touchablecomponent]

我的尝试:

<View style={styles.container}>
        <Button
        type={'outline'}
          title="login"
          titleStyle={{color:'white'}}
          containerStyle={{
            flex: 1,
            justifyContent: 'center',
            padding: 8,
          }}
          buttonStyle={{backgroundColor:'transparent', borderColor:'white'}}
          TouchableComponent={TouchableNativeFeedback.Ripple('red', false)}
        />
      </View>`

我得到的错误:

不变违规:元素类型无效:预期为字符串(对于内置组件)或类/函数(对于复合组件),但得到:对象。

版本:世博会版本 34.0.0,最新的反应原生元素版本。

任何帮助表示赞赏。

小吃:https ://snack.expo.io/@visfort/8cfad7

标签: react-nativebuttonexporeact-native-elements

解决方案


现在已经快一年了,但我自己也为此苦苦挣扎并最终找到了解决方案。

看起来该TouchableComponent属性接受字符串、函数或组件类。您不能传递组件本身。正因为如此,您会看到这将起作用:

<Button
  TouchableComponent={TouchableNativeFeedback} />

但是,您会看到这引发了异常

<Button
  TouchableComponent={<TouchableNativeFeedback />}

所以现在我们来解决问题。TouchableComponent确实接受一个功能。此函数必须返回可以呈现的 jsx。创建函数时,props将其传递下来。这些道具包含.children可用于在任何可触摸组件内呈现子级的属性。因此,你可以做这样的事情,这会给你一个红色的涟漪效应,例如:

<Button
  TouchableComponent={props => {
    return (
      <TouchableNativeFeedback background={TouchableNativeFeedback.Ripple("red")}>
        {props.children}
      </TouchableNativeFeedback>
    )
  }} />

现在,在我自己的项目中。我创建了一个辅助函数,可以动态创建它:

function createTouchableFromColor(color) {
  return props => {
    // Here you can also add additional logic if needed, 
    // eg: you want to use TouchableOpacity for ios
    <TouchableNativeFeedback background={TouchableNativeFeedback.Ripple(color)}>
      {props.children}
    </TouchableNativeFeedback>
  }
}

export { createTouchableFromColor };

这样,您只需导入该函数,它就变得容易多了:

import { createTouchableFromColor } from "./*the location of the file*"

<Button
  TouchableComponent={createTouchableFromColor("red")} />

推荐阅读