gpt4 book ai didi

javascript - '$' 在 React 组件 props 中起什么作用?

转载 作者:行者123 更新时间:2023-12-03 07:53:16 24 4
gpt4 key购买 nike

我正在研究 styled-component,在“根据 props 进行适配”部分遇到了一些问题。

import './App.css';
import styled from 'styled-components'

const PrimaryButton = styled.button`
color: ${props=>props.primary?"white":"black"};
background-color: ${props=>props.primary?"blue":"gray"};
`;

function App() {
return (
<div>
<PrimaryButton>Normal</PrimaryButton>
<PrimaryButton primary>Primary</PrimaryButton>
</div>
);
}

export default App;

起初,我尝试使用这段代码,控制台告诉我使用 primary=true,所以我就这样做了。

但是控制台中出现以下错误,提示“看起来未知的 prop“primary”正在发送到 DOM”。为了解决这个问题,我简单浏览了一下styled-components文档。我发现他们使用 $primary 而不是 primary。所以最终的代码如下所示:

import './App.css';
import styled from 'styled-components'

const PrimaryButton = styled.button`
color: ${props=>props.$primary?"white":"black"};
background-color: ${props=>props.$primary?"blue":"gray"};
`;

function App() {
return (
<div>
<PrimaryButton>Normal</PrimaryButton>
<PrimaryButton $primary>Primary</PrimaryButton>
</div>
);
}

export default App;

我不再看到错误,但我仍然不知道它发生的原因并已解决。

$ 是什么意思?

最佳答案

这些由 styled-components 使用而且它们与 React 无关。

If you want to prevent props meant to be consumed by styled components from being passed to the underlying React node or rendered to the DOM element, you can prefix the prop name with a dollar sign ($), turning it into a transient prop.

您可以了解更多here你可以找到一个例子。

关于javascript - '$' 在 React 组件 props 中起什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76626297/

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