简体   繁体   English

JSX对外部元素的条件修改

[英]JSX conditional modification of outer element

I'm trying to do something like this:我正在尝试做这样的事情:

render() {

  let a = <a className="nav-link" href={this.props.href} />

  if (this.props.hasCollapse) {
    a = <a className="nav-link"
           href={this.props.href}
           data-toggle="collapse"
           data-target={this.props.collapseId} />
  }

  return (

    {a}
      <i className="fas fa-fw fa-cog"></i>
      <span>{this.props.title}</span>
    {a}

)

} }

where the {a} in the return is replaced by the appropriate version as determined by the hasCollapse property.其中返回中的{a}hasCollapse属性确定的适当版本替换。 How might I achieve this?我怎样才能做到这一点?

You should change the properties for the link.您应该更改链接的属性。 For example例如

function AwesomeLink({ collapseId, hasCollapse, href, title }) {
  let hrefProps = {};

  if (hasCollapse) {
    hrefProps = {
      'data-toggle': 'collapse',
      'data-target': collapseId,
    };
  }

  return (
    <a className='nav-link' href={href} {...hrefProps}>
      <i className='fas fa-fw fa-cog' />
      <span>{title}</span>
    </a>
  );
}

I would do this with simple conditionals:我会用简单的条件来做到这一点:

const Link = (props) => {

    return (<a className="nav-link" 
    href={props.href}
    data-toggle={props.hasCollapse ? 'collapse' : null}
    data-target={props.hasCollapse ? props.collapseId : null}
    >
      <i className="fas fa-fw fa-cog"/>
      <span>{props.title}</span>
    </a>
  )
}

Also, it looks like you're setting data properties for usage with Bootstrap or a similar library.此外,您似乎正在设置用于 Bootstrap 或类似库的数据属性。 You may want to look into React Bootstrap and make use of their components designed to be used in React without dealing with messy DOM manipulation.你可能想研究一下React Bootstrap并利用它们设计用于 React 的组件,而无需处理混乱的 DOM 操作。

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

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