gpt4 book ai didi

css - 使用 React 时查找元素的宽度?

转载 作者:太空宇宙 更新时间:2023-11-04 10:31:18 24 4
gpt4 key购买 nike

我可以在 React 组件生命周期的哪个点获取在 css 文件中设置的组件 css 属性?

我已经在 render 方法和 componentDidMount 方法中尝试过,但都没有将 css 属性分配给组件。

export default class HomeArtist extends React.Component {
constructor(props){
super(props);
}
componentDidMount(){
let ImageStore = document.getElementsByClassName('home-artist-display');
console.log("ComponentDidMount: ", ImageStore);
}
render(){
var ImageStyle = {
backgroundImage: "url("+this.props.info.image+")"
};
return (
<div className="home-artist-display" style={ImageStyle}>
<Link to={"artist/" + this.props.info.id}>
<h3 className="home-artist-name">{this.props.info.name}</h3>
</Link>
</div>
)
}
}

最佳答案

我写了一个 React 库,它向组件公开一个 size 对象(带有宽度和高度属性)。

对于您的用例,您可以像这样使用它:

import SizeMe from 'react-sizeme';  // import me!   

class HomeArtist extends React.Component {
...
render(){
// Size gets passed in as props!
const { width, height } = this.props.size;

var ImageStyle = {
backgroundImage: "url("+this.props.info.image+")"
};
return (
<div className="home-artist-display" style={ImageStyle}>
<Link to={"artist/" + this.props.info.id}>
<h3 className="home-artist-name">{this.props.info.name}</h3>
</Link>
</div>
)
}
}

// wrap your component export!
export default SizeMe()(HomeArtist);

--

您可以在 https://github.com/ctrlplusb/react-sizeme 找到完整的详细信息

关于css - 使用 React 时查找元素的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36478200/

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