简体   繁体   English

在React中,如何基于传入的props动态渲染组件?

[英]How do you dynamically render a component based on incoming props, in React?

I have a component that I want to render that will render differently based on the incoming props: 我有一个要渲染的组件,该组件根据传入的道具会有所不同:

const Label = ({ data, attribute, style, link }) => (
  <Link to={link} style={style}>{data ? `${data[attribute]}` : ''}</Link>
);

style and link props are optional so I want to render component differently based on whether they exist or not - the only way I can think of doing it is like this, but the jsx is wrong. stylelink道具是可选的,因此我想根据组件是否存在来不同地渲染组件-我能想到的唯一方法就是这样,但是jsx是错误的。 What is the best practice in React? React的最佳实践是什么? Thanks. 谢谢。

const Label = ({ data, attribute, style, link }) => (
  if(link && style) { 
    <Link to={link} style={style}>{data ? `${data[attribute]}` : ''}</Link> 
  } else if (link) {
    <Link to={link}>{data ? `${data[attribute]}` : ''}</Link>
  }
  //...
);

I would do something like this: 我会做这样的事情:

const Label = ({ data, attribute, style, link }) => {
  if (link) {
    return (
      <Link to={link} style={style}>{data ? `${data[attribute]}` : ''}</Link>
    );
  }
  // ...
};

You should be able to safely pass undefined as the style prop 您应该能够安全地将undefined用作style道具

You can create a prop to be used specifically for the Link component and defining the propTypes accordingly. 您可以创建一个专门用于Link组件的道具,并相应地定义propTypes。 In the example below, the prop linkProps is spread in the Link component. 在下面的示例中,prop linkProps散布在Link组件中。

 // a simulation, just to make my point... const Link = props => (<div {...props} />); const Label = ({ data, attribute, linkProps = {}}) => ( <Link {...linkProps}> {data ? `${data[attribute]}` : ''} </Link> ); Label.propTypes = { data: React.PropTypes.object.isRequired, attribute: React.PropTypes.string.isRequired, linkProps: React.PropTypes.shape({ style: React.PropTypes.object, to: React.PropTypes.string }) }; class Main extends React.Component { render() { const data = { label: 'Hello!' }; const linkProps = { style: { fontWeight: 'bold' } }; return ( <div> <Label data={data} attribute='label' /> <Label data={data} attribute='label' linkProps={linkProps}/> </div> ) } } ReactDOM.render(<Main />, document.getElementById('main')); 
 <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="main"/> 

I hope it helps. 希望对您有所帮助。 ;) ;)

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

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