我有一个React组件,一个按钮,我需要将子元素的background-color设置为按钮的color。我知道您不应该在this.refs.myElement.getDOMNode()函数中调用render(),所以我不确定应该如何进行布局。

此刻,我的代码如下所示:

import React from 'react';
import { Button, Glyphicon } from 'react-bootstrap';
import classnames from 'classnames';

export default class GlyphButton extends Button {
    constructor(props) {
        super(props);
    }

    render() {
        let {
            glyph,
            className,
            children,
            ...props
        } = this.props;

        return (
            <Button ref='btn' {...props} className={classnames([className, 'glyph-button'])}>
                <Glyphicon glyph={glyph} />
                {children}
            </Button>
        );
    }
}


我需要做这样的事情:

let color = this.refs.btn.style.color;
return (
    <Button ref='btn' ...>
        <Glyphicon glyph={glyph} style={{backgroundColor: color}} />
        {children}
    </Button>
);


不幸的是,this.refs尚未被填充。

万一您好奇,我这样做的原因是因为我对某些图标使用了Glyphicon的免费版本PNG,这些图标在透明背景上都是黑色的,并且我在使用:

glyphicon.glyphicon-playing-dice:before {
   content: "";
   width: 20px;
   height: 20px;
   -webkit-mask-size: 100%;
   -webkit-mask-image: url(/img/glyphicons/glyphicons-playing-dice.png);
   display: block;
}


使它像一个字体图标。此类将使元素的background-color成为显示图标的颜色。

最佳答案

您可以将color设置为状态,然后在componentDidMount阶段进行更改。

getInitialState: function(){
   return {bgColor: ''}
 },
componentDidMount: function(){
   var color = React.findDOMNode(this.refs.btn).style.color;
    this.setState({bgColor : color});
}


因为React建议我们:


  您的第一个倾向通常是尝试使用引用在应用程序中“使事情成真”。如果是这种情况,请花点时间仔细考虑一下在组件层次结构中应在何处拥有状态。

10-08 08:12
查看更多