React中使用styled-components设置图片border-radius属性不生效如何解决?
问题原因&解决方法
- 错误1:React 中给元素加行内样式不能直接写
border-radius="50px",HTML 原生 img 标签不存在该属性,正确写法是通过style属性传入驼峰命名的样式对象:style={{borderRadius: '50px'}} - 错误2:styled-components 中不存在
styled.image这个标签写法,你定义的UserProfilePicture是包裹 img 的容器,应该改成styled.div;如果要直接给 img 加样式,才用styled.img - 补充:如果给父容器加 border-radius,需要额外加
overflow: hidden避免子元素 img 溢出容器,导致圆角看不到
修改后组件代码
import React from "react"; import { UserContainer, User, UserProfilePicture, UserProfileName, UserChevronIcon, } from "./User.style"; import Logo from "../../../images/ProfileFace.jpg"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faChevronDown } from "@fortawesome/free-solid-svg-icons"; function UserProfile() { return ( <UserContainer> <User> <UserProfilePicture> <img src={Logo} height="50" width="50" style={{borderRadius: '50px'}} /> </UserProfilePicture> <UserProfileName>Olivia Wilde</UserProfileName> <UserChevronIcon> <FontAwesomeIcon icon={faChevronDown} color="#7a7e7e" /> </UserChevronIcon> </User> </UserContainer> ); } export default UserProfile;
修改后styled-components样式代码
import styled from "styled-components"; export const UserContainer = styled.div` height: 90%; width: 30%; margin: 0px; padding: 0px; background-color: inherit; color: white; display: flex; flex-direction: row; align-items: flex-end; `; export const User = styled.div` height: 70%; width: 100%; background-color: inherit; display: flex; text-align: end; justify-content: space-around; `; export const UserProfilePicture = styled.div` height: 50%; width: 50%; border-radius: 100px; overflow: hidden; display: flex; justify-content: center; align-items: center; `; export const UserProfileName = styled.div` height: 40%; width: 40%; color: #7a7e7e; font-size: 17px; font-weight: 500; display: flex; align-items: center; justify-content: flex-start; `; export const UserChevronIcon = styled.div` height: 50%; width: 10%; display: flex; align-items: center; justify-content: flex-end; `;
内容的提问来源于stack exchange,提问作者WorstProgrammerEver
相关产品推荐
相关产品推荐

