繁体   English   中英

当组件在 React Native 中重新渲染时,动态不透明度不会改变

[英]Dynamic Opacity not changing when component rerenders in react native

我开始学习 React Native,并为我的项目创建了一个简单的 Button 组件以在我的项目中重用。 我根据变量“禁用”动态设置了不透明度值,但是,按钮的外观不会随着不透明度变量的值而改变。 找了一圈也没找到解释
任何帮助将不胜感激。

这是我的源代码:

import React from 'react'
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native'
import PropTypes from 'prop-types'

//TODO: arrumar o problema com a opacidade
export default function Button({text, onPress, style, disabled, textStyle}) {
    let opacity = disabled === true ? 0.5 : 1
    // console.log('opacity', opacity)
    return (
        <TouchableOpacity onPress={onPress} style={[defaultStyles.button, style, {opacity: opacity}]} 
            disabled={disabled}>
            <Text style={[defaultStyles.text, textStyle]}>{text}</Text>
        </TouchableOpacity>
    )

}

const defaultStyles = StyleSheet.create({
    text: {
        color: 'white'
    },
    button: {
        backgroundColor: 'black',
        margin: 15,
        padding: 15,
        borderRadius: 10
    },
})

Button.propTypes = {
    text: PropTypes.string,
    onPress: PropTypes.func,
    style: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.array,
        PropTypes.object
    ]),
    disabled: PropTypes.bool,
    textStyle: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.array,
        PropTypes.object
    ])
}

编辑:这是调用按钮的代码

class NewDeck extends Component {

    state={
        title: null
    }

    submit = () => {
        const { add, goBack } = this.props
        let deck = {...this.state}
        if(!deck['deckId']){
            deck['deckId'] = Date.now()
            deck['logs'] = []
        }

        !deck['cardsId'] && (deck['cardsId'] = [])

        add(deck).then(() => {
            this.props.navigation.navigate('Deck', {deckId: deck.deckId, title: deck.title})
            this.setState({title: null})
            }
        )
    }

    render(){
        const disabled = this.state.title === null || this.state.title.length === 0
        return (
            <KeyboardAwareScrollView resetScrollToCoords={{ x: 0, y: 0 }}
                contentContainerStyle={styles.container}>
                <Text style={textStyles.title2}>Whats the title of your deck?</Text>
                    <TextInput editable={true} style={[styles.input, textStyles.body]}
                    placeholder='Type title here'
                    maxLength={25}
                    value={this.state.title}
                    onChangeText={(text) => {
                        this.setState({title: text})
                    }}
                    />
                <Button
                    onPress={this.submit}
                    text='Submit'
                    style={{backgroundColor: colors.pink}}
                    textStyle={textStyles.body}
                    disabled={!this.state.title} 
                />
              </KeyboardAwareScrollView>
            )
    }
}

如果 newDeck 组件的标题为空或 null,则 disabled 变量为 true。 当这个变量为真时,按钮的不透明度应该只有 0.5。 当该值变为 false 时,不透明度再次变为 1。 如果我记录组件中不透明度的值,我可以看到它从 0.5 变为 1,但组件的外观没有改变。

不确定它是否是TouchableOpacity组件上的错误,但在单击该组件之前,不透明度不会在重新渲染时更新

要解决您的问题,只需将可触摸的内容包装在视图中并将不透明度应用于视图而不是可触摸

export default function Button({text, onPress, style, disabled, textStyle}) {
    const opacity = disabled === true ? 0.5 : 1
    // console.log('opacity', opacity)
    return (
        <TouchableOpacity onPress={onPress} disabled={disabled} 
          style={[defaultStyles.button, style]}>
          <View style={{opacity}}>
            <Text style={[defaultStyles.text, textStyle]}>{text}</Text>
          </View>
        </TouchableOpacity>
    )

}

在我看来,正确的解决方案是使用setOpacityTo方法。

在你的render

render() {
  const opacityValue = this.props.disabled ? 0.5 : 1;
  return (
    <TouchableOpacity style={{ opacity: opacityValue }} ref={(btn) => { this.btn = btn; }} onPress={this.onPress}>
      <Text>{this.props.text}</Text>
    </TouchableOpacity>
  );
}

接下来您可以在componentDidUpdatedisabled道具更改使用setOpacityTo方法:

  componentDidUpdate(prevProps) {
    const { disabled } = this.props;
    if (disabled !== prevProps.disabled) {
      const opacityValue = disabled ? 0.5 : 1;
      this.btn.setOpacityTo(opacityValue);
    }
  }

如果您使用的是React Native 0.63 及更高版本,那么 Pressable 是更优雅的解决方案,它的 Opacity 更改按预期工作。

<Pressable
    style={{
       opacity: item.isSelected ? 0.5 : 1
    }}>
       //Your button content goes here
</Pressable>

对我来说,当我还更改了disabled道具和不透明度时,它就起作用了。

我想问题是TouchableOpacity中的不透明度是一个Animated.Value ,它覆盖了style道具中的值并且不会改变,当style道具发生变化时......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM