android - 如何自定义TouchableOpacity并在各个组件中复用

标签 android react-native

我正在尝试使用以下样式自定义 TouchableOpacity

<TouchableOpacity
  onPress={() => {
    navigate("EnableNotification");
  }}
>
  <View
    style={{
      backgroundColor: "#FE434C",
      alignItems: "center",
      justifyContent: "center",
      borderRadius: 10,
      width: 240,
      marginTop: 30,
      height: 40
    }}
  >
    <Text style={{ color: "white" }}>CONTINUE</Text>
  </View>
</TouchableOpacity>

我在每个组件中都有这个 TouchableOpacity。我想要在一个 js 文件中自定义此 View 并重用它。无论我想在何处使用它,只需实现 onPressText。我怎样才能做到这一点?

最佳答案

这是我创建的其中一个按钮的 fragment 。 textStyle 和 buttonStyle 都在这个组件中被排除在外,但是如果你希望它们是可变的,你可以通过 RoundButton = ({ textStyle, buttonStyle })

传递它
const RoundButton = ({ onPress, children }) => {

  return (
    <TouchableOpacity onPress={onPress} style={buttonStyle}>
      <Text style={textStyle}>{children}</Text>
    </TouchableOpacity>
  );
};

这是一个用例:

<RoundButton onPress={this.onSubmit.bind(this)>Confirm</RoundButton>

所以,你可以去:

const Button = ({ onPress, buttonText }) => {
  const { buttonStyle, textStyle } = styles;

  return (
    <TouchableOpacity onPress={onPress} style={styles.button}>
      <Text style={{ color: '#fff' }}>{buttonText}</Text>
    </TouchableOpacity>
  );
};

const styles = {
  backgroundColor: '#FE434C',
  alignItems: 'center',
  justifyContent: 'center',
  borderRadius: 10,
  width: 240,
  marginTop: 30,
  height: 40,
}

然后 从 '../somepath/Button.js; 导入 { Button };

它将成为可用的自定义 JSX 元素。

return (
...

<Button onPress={() => navigate('EnableNotification'}>CONTINUE</Button>

...
)

编辑:传递样式的更新:

const Button = ({ onPress, buttonText, buttonStyle, textStyle }) => {

      return (
        <TouchableOpacity onPress={onPress} style={buttonStyle}>
          <Text style={textStyle}>{buttonText}</Text>
        </TouchableOpacity>
      );
    };

您的用例是:

import { Button } from '../somepath/Button.js';

class MyPage extends Component {
  render() {
    return (
      ...
      <Button buttonStyle={styles.yourStyle} textStyle={styles.yourStyle2} onPress={() => navigate('EnableNotification')>CONTINUE</Button>
      ...
    )
  }
}

const styles = {
  yourStyle: {
    ...
  }

  yourStyle2: {
    ...
  }
}   

关于android - 如何自定义TouchableOpacity并在各个组件中复用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43678025/

相关文章:

java - 如何从非 Activity 类开始一个 Activity 并等到它完成?

Android SDK - 设置具有相同 Intent 不同附加功能的多个警报

android - 匹配 <intent-filter> 中的 url 模式

android - 如何使用来自其他 Activity 的 singleInstance Activity 重新启动 Activity

android - 如何在 React Native 中全局声明字符串

react-native - 找不到变量 __fbbatchedbridge (<未知文件> : 1)

android - 为什么我不能在构建脚本中使用 gradle task connectedDebugAndroidTest?

javascript - 在 JSX 中显示来自对象的结果

arrays - 如何在 native react 中将json数据与数组映射

javascript - TabNavigator 如何使用 tabBarComponent?标签栏不显示