【问题标题】:Creating a React Button Component, Importing it and adding Text to the Button创建一个 React Button 组件,导入它并将文本添加到 Button
【发布时间】:2020-12-10 12:26:20
【问题描述】:

所以我正在尝试创建一个可重用的 React 按钮组件,我可以将其导入到其他组件中。

我创建了组件,将其导出,然后将其导入到我想要使用它的其他组件中。

现在,如果我在其他组件中使用<Button>TEXT</Button>,则不会出现 TEXT。很明显,我是一个 React 菜鸟。

React 按钮组件:

import React from 'react';
import styled from 'styled-components';

const Button = styled.button`
    width: 138px;
    height: 35px;
    text-align: center;
    letter-spacing: 0px;
    color: #FFFFFF;
    background: #5DA7DE 0% 0% no-repeat padding-box;
    box-shadow: 10px 10px 10px #00000066;
    opacity: 0.86;
    color: white;
`;

export const ButtonBlue = () => {
  return (
<Button/>
  );
};

我想在其中使用 Button 的 React 组件:

import React from 'react'
import styled from 'styled-components';
import { ButtonBlue as Button } from '../Buttons/ButtonBlue.jsx'

const Container = styled.div`
    width: 80%;
    min-height: 300px;
    margin: auto;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: 1fr;
    grid-column-gap: 0px;
    grid-row-gap: 0px;
    margin-bottom: 100px;
`

export const LandingBottomLatestEvents = () => {
    return (
    <Container>
        <Button>TEXT</Button>
    </Container>
    )
}

查了谷歌,但目前找不到解决方案。

任何帮助表示赞赏。谢谢!!

【问题讨论】:

    标签: reactjs button components


    【解决方案1】:

    每当你在标签之间写东西时

    <Component>Hello World</Component>
    

    您可以使用组件中的 children 道具

    const Component = ({children}) => {
      console.log('children', children) // Hello World
      return <h1>{children}</h1>
    }
    

    【讨论】:

    • 太棒了!这样可行!但是您必须使用关键字“孩子”,对吗?我用 {text} 试过了,但没有用。
    • 是的@StefanRows,props.children
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 2019-01-22
    相关资源
    最近更新 更多