React创建一个水平分隔线,中间插入文本

我需要创建一个React组件,它是一个水平分隔线,其内容介于两者之间。我在线上的所有资源都无法帮助我完成此任务。我通过创建Divider组件并将文本放置在中间的方式来尝试了Material-ui分隔器,如下例所示:

<Divider>Or</Divider>

但是我得到了错误:

hr is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.

我需要在下图中实现此目的:

Display a horizontal Divider

任何帮助将不胜感激。

这些是我的以下代码:

 import React from 'react';
 import { makeStyles } from '@material-ui/core/styles';
 import List from '@material-ui/core/List';
 import Divider from '@material-ui/core/Divider';

 const useStyles = makeStyles((theme) => ({
   root: {
   width: '100%',
   maxWidth: 360,
   backgroundColor: theme.palette.background.paper,
 },
 }));

 export default function ListDividers() {
 const classes = useStyles();

 return (
 <List component="nav" className={classes.root} aria-label="mailbox 
 folders">

  <Divider>Or</Divider>

  </List>
  );
 }
评论
  • ket
    ket 回复

    Here a custom example of what you could do : repro on stackblitz (Just clean up the css, i added it directly in the jsx so i can paste it here easily)

    import React, { Component } from "react";
    import { render } from "react-dom";
    import Hello from "./Hello";
    import "./style.css";
    
    const App = () => {
      return <Divider>Or</Divider>;
    };
    
    const Divider = ({ children }) => {
      return (
        <>
          <div style={{ borderBottom: "1px solid black", marginBottom: "-10px" }} />
          <div style={{ textAlign: "center" }}>
            <span style={{ backgroundColor: "#FFFFFF", padding: "10px" }}>
              {children}
            </span>
          </div>
        </>
      );
    };
    
    render(<App />, document.getElementById("root"));
    
    

    这只是个主意,您可以使用flexbox避免像这样设置css属性。