使用Props来设置子元素的样式

huangapple go评论69阅读模式
英文:

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

&lt;StyledToolbar&gt;
   &lt;Logo sx={{display: &quot;block&quot;, width: 130}}  /&gt;
   ...
&lt;/StyledToolbar&gt;

Logo.jsx


const Logo = (props) =&gt; {
    return (
        &lt;img src=&quot;/assets/logo.svg&quot;
             alt=&quot;My Logo&quot;
             style={props.sx}
        /&gt;
    )
}
export default Logo

The logo is displayed but it is not styled correctly. Rendered HTML looks like this:
&lt;img src=&quot;/assets/logo.svg&quot; alt=&quot;My Logo&quot; style=&quot;width: 30px; height: 30px;&quot;&gt;

答案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

&lt;StyledToolbar&gt;
   &lt;Logo style={{display: &quot;block&quot;, width: 130}}  /&gt;
   ...
&lt;/StyledToolbar&gt;

Child Component

const Logo = (props) =&gt; {
    return (
        &lt;img src=&quot;/assets/logo.svg&quot;
             alt=&quot;My Logo&quot;
             style={props.style}
        /&gt;
    )
}
export default Logo

huangapple
  • 本文由 发表于 2023年7月28日 01:17:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76782097.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定