首页 文章

当道具更新时,React Native组件不透明度不会更新

提问于
浏览
3

我有一个React Native子组件,如果 disabled prop设置为true,则会将按钮呈现为半透明状态 . app最初加载后(一旦获得数据)可能会更新,因此不会是组件的初始状态 .

我可以看到,一旦我与按钮交互,它就会改变它的状态,但出于某种原因,之前没有 . 我可以从日志和 onPress 行为中看到道具正在更新 . 我尝试了不同的方法,但似乎没有解决问题 .

class TestButton extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {
    const buttonOpacity = (this.props.disabled  ? disabledOpacity : 1.0);
    console.log ("test disabled", this.props.disabled, buttonOpacity);

    return (
      <BubbleText style={{opacity: buttonOpacity}} onPress={
        () => ! this.props.disabled && doSomething() }>
          { this.props.testNumber }
      </BubbleText>
    );
  }
}

4 回答

  • 0

    设置TouchableOpacity按钮的不透明度似乎存在问题 . 我正在使用react-native@0.55.4 . 如果设置了不透明度然后更新,则新渲染似乎不会更改不透明度值,即使它未传递给组件样式 .

    使用 TouchableOpacity 可以使用本机方式执行此操作 . 如果使用 disabled 道具,也可以禁用所有新闻事件 .

    <TouchableOpacity
        disabled={ this.props.is_disabled }
        activeOpacity={ this.props.is_disabled ? .6 : 1 }>
        <Text>Custom Button</Text>
    </TouchableOpacity>
    

    有一点需要注意,设置 activeOpacity 似乎不会改变文本的不透明度只有backgroundColor .

    或者,使用 rgba 值指定不透明度确实有效 .

    export class CustomButton extends Component {
    
        get_button_style() {
            let _button_style = [this.props.button_style]
    
            if (this.props.is_disabled) {
                _button_style.push({
                    backgroundColor: 'rgba(0, 0, 0, .6')
                });
            }
    
            return _button_style;
        }
    
        render() {
            return(
                <TouchableOpacity
                    style= { this.get_button_style() }>
                    <Text> Custom Button </Text>
                </TouchableOpacity>
            )
        }
    }
    
  • 3

    很难说只是从代码片段中说,问题可能出在使用这个问题的父组件中 . 添加代码可能有助于确定问题所在 .

    对不起,没有足够的代表来添加评论 .

  • 0

    底层组件是 TouchableOpacity . 外部设置不透明度似乎存在问题 . 我在这种情况下通过明确定义颜色而不是使用不透明度来解决问题:

    class TestButton extends React.Component {
    
      constructor(props) {
        super(props);
      }
    
      render() {
          return (
            <BubbleText fill={this.props.disabled ? disabledFill : undefined} textStyle={this.props.disabled ? {color: disabledText} : {}} onPress={
              () => ! this.props.disabled && loadTest(this.props.navigator, this.props.set + this.props.testNumber, this.props.children)
              }>
                { this.props.testNumber }
              </BubbleText>
              );
    
      }
    }
    

    在我的代码的另一部分中,我添加了一个条件来将组件渲染为具有不透明度的 View (如果已禁用),如果不是,则添加 TouchableOpacity .

  • 0

    好像是一个已知的问题https://github.com/facebook/react-native/issues/17105

    一种解决方法是将TouchableOpacity的内容包装在视图中,并将不透明样式应用于该视图,而不是直接应用于Touchable不透明度 .

相关问题