如何将图像定义为背景按钮

时间:2017-07-23 10:12:01

标签: react-native

我尝试使用此代码将图片作为按钮的背景:

  <Button  style= {styles.btn }>
      <Image source={ require('.src.png')}  style={styles.img}/>
      <Text> title </Text> 
  </Button>

但我没有得到正确的结果 请帮忙

3 个答案:

答案 0 :(得分:4)

Button元素具有非常特殊的用途,尝试使用TouchableOpacity,同样,你的Text必须是绝对的才能出现在Image上:

import {TouchableOpacity, Text, Image, View, StyleSheet } from 'react-native';

const button = () =>
    <TouchableOpacity style={styles.btn}>
        <View style={styles.absoluteView}>
            <Text>title</Text>
        </View>
        <Image source={require('.src.png')}  style={styles.img}/>
    </TouchableOpacity>;

const styles = StyleSheet.create({
    absoluteView: {
        flex: 1,
        position: 'absolute',
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: 'transparent'
    },
    img: {...},
    btn: {...}
});

答案 1 :(得分:1)

这是一个简单的ImageButton

import React from 'react'
import { TouchableOpacity, View, Image, Text, StyleSheet } from 'react-native'
import images from 'res/images'
import colors from 'res/colors'

export default class ImageButton extends React.Component {
  render() {
    return (
      <TouchableOpacity style={styles.touchable}>
        <View style={styles.view}>
          <Text style={styles.text}>{this.props.title}</Text>
        </View>
        <Image
          source={images.button}
          style={styles.image} />
      </TouchableOpacity>
    )
  }
}

const styles = StyleSheet.create({
  view: {
    position: 'absolute',
    backgroundColor: 'transparent'
  },
  image: {

  },
  touchable: {
    alignItems: 'center',
    justifyContent: 'center'
  },
  text: {
    color: colors.button,
    fontSize: 18,
    textAlign: 'center'
  }
})

答案 2 :(得分:0)

像这样使用“react-native”中的 TouchableOpacity 和 ImageBackground:

import React from "react";
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  ImageBackground,
} from "react-native";

export default function App() {
  return (
    <View style={styles.container}>
      <TouchableOpacity onPress={() => alert("Button pressed")}>
        <ImageBackground source={require("./assets/anImage.png")} style={{}}>
          <Text style={styles.title}>Press Me</Text>
        </ImageBackground>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
  title: {
    color: "white",
    fontSize: 24,
    padding: 20,
  }
});