React 组件不接受 JSX 元素作为道具

React component is not accepting JSX Element as prop

我会将组件呈现为 Label 内容而不是字符串。

实际上我遇到了这个错误:

The shorthand prop for "Box" component was passed a JSX element but this slot only supports string|number|object|array|ReactElements.

import AudioItem from '../containers/Media'
const AudioLabel = (props) => {
    let url = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"
    const [audio] = useState(new Audio(url));
    const [isPaused, setIsPaused] = useState(audio.paused)
    return (<Label content={({ ...props }) => (<><span>{props.content}</span> <AudioItem isPaused={isPaused} setIsPaused={setIsPaused} audio={audio} /></>)}
        circular
        image={{
            src: 'public/images/avatar/small/matt.jpg',
            avatar: true,
        }}
        icon={
            <CloseIcon
            />}
    />)
}
export default AudioLabel

调用组件作为 prop.

import { Button, Header, List, RadioGroup, ItemLayout } from '@fluentui/react-northstar'
import { PlayIcon, PauseThickIcon } from '@fluentui/react-icons-northstar'

const AudioItem = (props) => {
    return (
        <ItemLayout
            headerMedia={<Button icon={props.isPaused ? (<PlayIcon />) : (<PauseThickIcon />)} onClick={() => { props.isPaused ? props.audio.play() : props.audio.pause(); props.setIsPaused(props.audio.paused) }} text content={props.isPaused ? "Play" : "Pause"} />}
        />
    )
}

如何将组件(带有 props)作为 content 传递?

问题reproduction

任意函数不是函数组件。如果你想让 React 将函数编译为组件,你需要 (a) 范围内的标识符和 (b) 大写字母作为该标识符的首字母。 doc.

要使您的代码正常工作,您需要创建一个新组件来呈现您的跨度和 AudioItem。

这里的工作示例:code

我会说将 JSX 作为 props 传递并不是最好的主意,但如果你确定那是你想要的,你总是可以将它转换为字符串,然后传递它,然后再将它转换回来;像这样(简单的例子):

const JSXToPass = () => {
    return (
        <div> example </div>
    );
}

const Parent = () => {
    return (
        <Child content={React.renderToString(JSXToPass)} />
    );
}

const Child = (props) => {
    return (
        <div dangerouslySetInnerHTML={{__html: props.content}} />
    );
}

我检查了 fluentdocumentation。您要实现的目标称为 render props in react。但是 fluent library 将其命名为 Shorthand Props

根据他们的文档,您需要遵循特定的模式才能实现此目的。在这里我添加了 Label Component 的代码并消除了错误。 sandbox_link

<Label
      content={{
        chidren: ({ ...props }) => (
        <>
          <span>{props.content}</span>
            <AudioItem
              isPaused={isPaused}
              setIsPaused={setIsPaused}
              audio={audio}
            />
        </>)
      }}
      circular 
      image={{
        src: "public/images/avatar/small/matt.jpg",
        avatar: true
      }}
      icon={<CloseIcon />}
    />