React:如何以编程方式设置 React 组件中元素的宽度和高度

use*_*413 1 css reactjs

我想根据一些计算以编程方式设置容器的宽度和高度。

我正在尝试设置我为 componentDidUpdate() 中的元素创建的 ref 的样式,但它没有效果

export default class CanvasOverlay extends React.Component {
    static propTypes = {
        imageURI : PropTypes.string.isRequired,
    };

    constructor(props) {
        super(props);
        this.width = 0;
        this.height = 0;
        this.canvasOverlay = React.createRef();
    }

    componentDidMount() {
        let image = new Image();
        let that = this;
        image.onload = function() {
            that._updateDimension(image.width, image.height);
        };
        image.src = this.props.imageURI;
    }

    _updateDimension(imageWidth, imageHeight) {
        const canvasOverlay = this.canvasOverlay.current;
        //Ideally there should be some calculations to get width and 
         height
        canvasOverlay.style.width = 480;
        canvasOverlay.style.height = 400;
    }

    render() {
        return(
            <div ref={this.canvasOverlay}>
                <Canvas imageURI={this.props.imageURI}/>
            </div>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

HTML 元素 canvasOverlay 应该调整大小,但它没有

Ran*_*lta 5

元素的style.widthandstyle.height不接受带有类型编号的值,因此您应该将其转换为字符串并添加一个'px'单位。

element.style.width = `${width}px`;

// or

element.style.width = width + 'px';
Run Code Online (Sandbox Code Playgroud)