React:在不使用this.props.children的情况下将组件作为prop传递

san*_*a-p 2 javascript jsx reactjs

我有一个组件Foo.js:

// a svg component with a star.svg icon
import { IconStar } from 'react-svg-icons'; 

// call a button with a custom icon
<Button icon={ IconStar }> Click to trigger </Button>
Run Code Online (Sandbox Code Playgroud)

然后button.js我有:

render() {
  const theIcon = this.props.icon;
  return (
    <button>
      {this.props children}
      {icon() /*this works but i can't pass props inside it*/} 
      <theIcon className={ Styles.buttonIcon } />
    </button>
  )
}
Run Code Online (Sandbox Code Playgroud)

我想在<IconStar>里面渲染<Button>,我该怎么做?

我不能通过这个,this.prop.children因为它在图标道具周围有更多的逻辑,但在这种情况下我只显示一个演示.

谢谢

paw*_*wel 5

您唯一遗漏的是JSX要转换为JS自定义组件应该以大写字母开头,例如<TheIcon />,小写字母表示本机DOM元素,例如<button />:

render() {
  const TheIcon = this.props.icon;  // note the capital first letter!
  return (
    <button>
      {this.props children}
      <TheIcon className={ Styles.buttonIcon } />
    </button>
  )
}
Run Code Online (Sandbox Code Playgroud)

https://jsfiddle.net/03h2swkc/3/