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

React Native component opacity not updating when props updated

我有一个 React Native 子组件,如果 disabled 属性设置为 true,它会以半透明状态呈现一个按钮。该 prop 可能会在应用程序初始加载后更新(一旦它获得了数据),因此不会是组件的初始状态。

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

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>
    );
  }
}

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

抱歉,没有足够的代表来添加评论。

底层组件是 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

设置 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 似乎不会仅更改背景颜色来更改文本不透明度。

或者使用 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>
        )
    }
}

似乎是一个已知问题 https://github.com/facebook/react-native/issues/17105

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

使用react-native-gesture-handler中的TouchableOpacity,它有一个名为containerStyle的道具,当“this.props.is_disabled”为false或true时,你的TouchableOpacity会自动更新不透明度。没有它,您将需要重新启动应用程序以显示不透明度:

<TouchableOpacity onPress={() => {}} 
                    disabled={this.props.is_disabled} 
                    containerStyle={{
                        opacity: this.props.is_disabled ? 1 : .4,
                    }}
                    style={}>
                </TouchableOpacity>