【问题标题】:How to use TouchableComponent prop in react native element button?如何在反应原生元素按钮中使用 TouchableComponent 道具?
【发布时间】:2019-11-20 21:09:34
【问题描述】:

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

我得到错误:

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

版本:expo 版本 34.0.0,最新的 react native elements 版本。

感谢任何帮助。

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

【问题讨论】:

    标签: react-native button expo react-native-elements


    【解决方案1】:

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

    看起来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")} />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多