How to set div height in react: 1. Implement div height through css; 2. Declare an object C in state and store the style of the change button in the object, then get A and reset C Just click "marginTop" in it.
The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.
How to set div height in react?
react dynamically sets element height
Use react to implement Dynamic modification of style (this method is not recommended unless there is no Other options)
As shown in the figure below:
The replacement button in the implementation diagram follows In the lower right corner of the image, when the height of the image changes, the position of the change button also changes.
1. Implement through css (there is no solution for the time being)
2. Use the characteristics of react data-driven view
2.1 Data: declare one in state Object C, which stores the style of the change button.
2.2 Operation: Let A = picture height, B = change button height. After the image is loaded, obtain A and set the marginTop in C again. (This idea only needs to change the data and does not need to consider the view layer)
construct
this.state = { updateBtnStyle :{ fontSize: "12px",marginLeft:'20px',marginTop:'300px', } } //在class中定义的函数,如果需要使用到全局this,需要此操作 this.loading = this.loading.bind(this)
Declare the operation function loading
loading(){ const imgHeight = document.getElementById('facePhoto').height console.log('图片的高度',document.getElementById('facePhoto')?.height) if(imgHeight === Number.parseInt(this.state.updateBtnStyle.marginTop)+24) return else{ this.setState({ updateBtnStyle:{ marginTop:document.getElementById('facePhoto')?.height-24+'px' } }) } }
View layer Pseudocode
<Item label="人脸照片" style={{ position: "relative" }} required> <img id={'facePhoto'} src={photo} alt="" width="300" onLoad={this.loading} style={{float:'left'}}/> <Button size="small" style={updateBtnStyle} onClick={() => StateManage.set(updatePhotoProps, { visible: true })}>更换</Button> </Item>
1. Obtain the height of the image:
1.1 Acquisition time: You need to wait for the image to be loaded to complete to obtain its height before it is effective, so you need to use The onLoad event of img ensures that the image has been loaded when the height of the image is obtained.
1.2 How to obtain: The width and height of the picture are set through the attributes height and width, not through style, so the method for obtaining the height is =document.getElementById('xxx').height
2. The declared function does not have Binding this makes it impossible to use setState
Recommended learning: "react video tutorial"
The above is the detailed content of How to set div height in react. For more information, please follow other related articles on the PHP Chinese website!