React - 如何动态创建属性

React - how to create attributes dynamically

我有 2 个属性连接到 2 个道具:aria-hiddenaria-label
aria-hidden 为真时,它只显示那个。如果为假,则仅显示 aria-label.

我写了这段代码,但它不是 DRY...我该如何改进它?

 render() {
     let svgMarkup = '';

        if (this.props.hidden) {
            svgMarkup = (
                <svg role="img" aria-hidden="true">
                    ...
                </svg>
            );
        } else {
            svgMarkup = (
                <svg role="img" aria-label={ this.props.label }>
                    ...
                </svg>
            );
        }

        return svgMarkup;
 }

您可以在普通对象上设置 props,然后使用扩展语法将 props 应用到您的 React 组件:

render() {
    const ariaProps = this.props.hidden ?
        { 'aria-hidden': 'true' }
        :
        { 'aria-label': this.props.label };

    return (
        <svg role="img" {...ariaProps}>
            ...
        </svg>
    );
}