React Native,TouchableOpacity包装浮动按钮什么都没得到

b.b*_*ben 5 android floating-action-button react-native

我正在创建一个简单的动作按钮(浮动按钮)

这是有效的:

<View style={{
    width: this.props.size,
    height: this.props.size,
    borderRadius: this.props.size / 2,
    backgroundColor: '#ee6e73',
    position: 'absolute',
    bottom: 10,
    right: 10,
    flexDirection:'row'
}}>
    <Text>
        +
    </Text>
</View>
Run Code Online (Sandbox Code Playgroud)

这不是 :

<TouchableOpacity
        onPress={()=>{
        }} >
    <View style={{
        width: this.props.size,
        height: this.props.size,
        borderRadius: this.props.size / 2,
        backgroundColor: '#ee6e73',
        position: 'absolute',
        bottom: 10,
        right: 10,
        flexDirection:'row'
    }}>
        <Text>
            +
        </Text>
    </View>
</TouchableOpacity>
Run Code Online (Sandbox Code Playgroud)

只需使用TouchableOpacity包装,然后我的按钮就不会出现任何错误.

React 0.1.7,Android

然后我尝试从View到TouchableOpacity移动样式,这是工作

<TouchableOpacity
        onPress={()=>{
        }} 
        style={{
            width: this.props.size,
            height: this.props.size,
            position: 'absolute',
            borderRadius: this.props.size / 2,
            backgroundColor: '#ee6e73',
            bottom: 10,
            right: 10,
        }}>
    <Text>
        +
    </Text>
</TouchableOpacity>
Run Code Online (Sandbox Code Playgroud)

谁能解释一下为什么?

React Native docs说

[ https://facebook.github.io/react-native/docs/touchableopacity.html] [1 ]

用于使视图正确响应触摸的包装器.这样做是在不实际更改视图层次结构的情况下完成的,并且通常很容易添加到应用程序而不会产生奇怪的副作用.

这意味着我将原始视图包装起来,它会像我预期的那样工作,但事实并非如此.

Sud*_*Plz 12

根据我的经验,TouchableOpacity对absolute定位不起作用.也许如果你删除它,onPress将再次工作.

另请注意,首先渲染的元素和最后渲染的元素非常重要.

例如,如果你这样做:

<View>
    <TouchableOpacity style={{position:'absolute'}} onPress={()=> 
           {console.log("It works or not?")}}>
   </TouchableOpacity>
    <Text style={styles.aStyle}>
        Some text bla bla
    </Text>
</View>
Run Code Online (Sandbox Code Playgroud)

这是一个非常好的机会,文本将呈现在TouchableOpacity,因此你将无法得到onPress工作.

然后由于该位置是绝对的,您所要做的就是将其渲染为View的最后一个子节点:

<View>
    <Text style={styles.aStyle}>
        Some text bla bla
    </Text>
    <TouchableOpacity style={{position:'absolute}} onPress={()=> 
       {console.log("It works or not?")}}>
   </TouchableOpacity>
</View>
Run Code Online (Sandbox Code Playgroud)


Dan*_*ein 6

flex: 1我知道这已经很旧了,但我遇到了这个问题,并且在添加到我的 TouchableOpacity之前,上述任何操作都不起作用。