简体   繁体   English

React:将组件作为道具传递而不使用 this.props.children

[英]React: Pass component as prop without using this.props.children

I have this a component Foo.js :我有一个组件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>

And then on button.js I have:然后在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>
  )
}

I want to render <IconStar> inside <Button> , how do I do that?.我想在<Button>内渲染<IconStar> <Button> ,我该怎么做?

I can't pass this as this.prop.children because it has more logic around the icon prop, but in this case I'm showing only a demo.我不能将它作为this.prop.children传递,因为它有更多关于图标道具的逻辑,但在这种情况下,我只展示了一个演示。

Thanks谢谢

The only thing you have missed is that for JSX to transpile to JS custom components should be named starting with a capital letter, eg <TheIcon /> , while lowercase letter signifies native DOM elements, eg <button /> .:您唯一错过的是 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>
  )
}

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

If your using es6 then you can use a spread operator to pass the attributes to a below component, I think that might solve your problem:如果您使用 es6,那么您可以使用扩展运算符将属性传递给以下组件,我认为这可能会解决您的问题:

 var MyIcon = (props) => { return <i {...props}> { props.className } < /i> }; var MyButton = (props) => { return ( < button > { props.children }<MyIcon {...props} />< / button > ); } ReactDOM.render( < MyButton className = 'my-icon'>My Button Text</MyButton> , document.getElementById('myComponent') )
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id='myComponent'></div>

so the ...props will pass myProps into IconStar.所以 ...props 会将 myProps 传递给 IconStar。 Obviously you can pass anything you want through.显然你可以通过任何你想要通过的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM