【问题标题】:React Native is there an attribute equals to alt on image componentReact Native是否有一个属性等于图像组件上的alt
【发布时间】:2019-12-31 07:35:42
【问题描述】:

来自 reactjs,我期待图像组件上的“alt”属性在无法加载图像的情况下显示文本。 我阅读了文档here,发现最接近的是 on error 事件。

React Native 图像组件中是否有等于 alt 的属性?如果我没有 alt 属性,用默认文本替换图像的最简单方法是什么?

【问题讨论】:

    标签: react-native react-native-image react-native-component


    【解决方案1】:

    您可以自己制作这样的组件,它只需要非常少的代码。这是一个基本示例:

    export default class AccessibleImage extends Component {
    
        state = {
            error : false
        };
    
        _onImageLoadError = (event) => {
            console.warn(event.nativeEvent.error);
            this.setState({ error : true });
        }
    
        render() {
            const { source, alt, style } = this.props;
            const { error } = this.state;
    
            if (error) {
                return (
                    <Text>{alt}</Text>
                );
            }
    
            return (
                <Image 
                    accessible
                    accessibilityLabel={alt}
                    source={source} 
                    style={style}
                    onError={this._onImageLoadError} />
            );
        }
    }
    

    如果加载图像时出现错误,这将显示提供的alt,并将该文本用作更接近网络行为的屏幕阅读器的accessibilityLabel

    【讨论】:

    • Tnx 很多!只是想确保我没有错过任何东西。我想知道他们为什么不将 alt 属性添加为 javascript 中的默认行为。
    猜你喜欢
    • 2016-11-17
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多