gpt4 book ai didi

css - react : How to set width and height of an element in react component programatically

转载 作者:行者123 更新时间:2023-12-05 00:58:54 28 4
gpt4 key购买 nike

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

我正在尝试设置我为 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>
);
}
}

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

最佳答案

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

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

// or

element.style.width = width + 'px';

关于css - react : How to set width and height of an element in react component programatically,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55913642/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com