如何在使用样式化组件进行样式化的反应中更改按钮组件中的 2 个跨度内容?

问题描述 投票:0回答:2

我想创建一个使用 html 的按钮组件,如下所示。

<button class="button_57" role="button">
   <span class="text">Button</span>
   <span>Alternate text</span>
</button>

我希望能够使用一个由 React 创建的 Button 组件。

<CustomButton {...otherProps}>{children}</CustomButton>

有没有办法用这样的道具修改 Button 组件中的 span 内容?

<Button span_content1={''} span_content2={''}></Button>

我只发现过小时候工作。

<Button>
   <span class='text'>Button</span>
   <span>Alternate text</span>
</Button>
javascript css reactjs styled-components
2个回答
0
投票

使用 React 时,我们可以创建这样的组件

function ButtonName({ content1, content2}) {
   return(
      <Button>
         <span class='text'>{content1}</span>
         <span>{content2}</span>
      </Button>
   )
}

创建组件后,我们可以这样调用组件名称。

<ButtonName content1="Button" content2="Alternate text" />

要更改内容,我们可以将content1和content2替换为其他值


0
投票

import styled from 'styled-components';

// Define your styled component
const CustomButton = styled.button`
  // Add your styles here
`;

const Button = ({ span_content1, span_content2, ...props }) => (
  <CustomButton {...props}>
    <span>{span_content1}</span>
    <span>{span_content2}</span>
  </CustomButton>
);

// Use your component
<Button span_content1="Button" span_content2="Alternate text" />

Button 组件接受 span_content1 和 span_content2 作为 props 并将它们用作两个 span 元素的内容。其余的道具(...道具)被转发到 CustomButton 组件。

https://react.dev/learn/passing-props-to-a-component

https://styled-components.com/docs/basics#adapting-based-on-props

© www.soinside.com 2019 - 2024. All rights reserved.