英文:
Use Props for child element style
问题
在React项目中,我有一个父组件和一个子组件。我想将props传递给子组件,并在子组件中用于样式设置。
父组件:
<StyledToolbar>
<Logo sx={{display: "block", width: 130}} />
...
</StyledToolbar>
Logo.jsx:
import React from 'react';
const Logo = (props) => {
return (
<img src="/assets/logo.svg"
alt="My Logo"
style={props.sx}
/>
)
}
export default Logo;
Logo被显示出来,但样式不正确。渲染的HTML看起来像这样:
<img src="/assets/logo.svg" alt="My Logo" style="width: 30px; height: 30px;">
英文:
In React project I have a parent and a child component. I want to pass the props down and use those for styling in the child component.
Parent
<StyledToolbar>
<Logo sx={{display: "block", width: 130}} />
...
</StyledToolbar>
Logo.jsx
const Logo = (props) => {
return (
<img src="/assets/logo.svg"
alt="My Logo"
style={props.sx}
/>
)
}
export default Logo
The logo is displayed but it is not styled correctly. Rendered HTML looks like this:
<img src="/assets/logo.svg" alt="My Logo" style="width: 30px; height: 30px;">
答案1
得分: 1
在React
中,您通过style
属性传递样式对象。所以您使用的sx
的逻辑不起作用。
以下是正确的代码:
父组件
<StyledToolbar>
<Logo style={{display: "block", width: 130}} />
...
</StyledToolbar>
子组件
const Logo = (props) => {
return (
<img src="/assets/logo.svg"
alt="My Logo"
style={props.style}
/>
)
}
export default Logo
英文:
In React
you pass the style object via the style prop. So your logic with the sx
doesn't work.
Here is the correct code:
Parent Component
<StyledToolbar>
<Logo style={{display: "block", width: 130}} />
...
</StyledToolbar>
Child Component
const Logo = (props) => {
return (
<img src="/assets/logo.svg"
alt="My Logo"
style={props.style}
/>
)
}
export default Logo
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论