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

Ada*_*ski 6 javascript jsx react-native mobx

我有一个React Native子组件,如果disabledprop被设置为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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

kgs*_*tew 7

设置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>
Run Code Online (Sandbox Code Playgroud)

有一点需要注意,设置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>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 另一种选择是将 TouchableOpacity 包装在视图中。然后在视图中设置不透明度。 (2认同)