渲染”;a“;React.js中的可选href

Rendering "a" with optional href in React.js

本文关键字:href React 渲染 js      更新时间:2023-09-26

我需要在其中一列中呈现一个带有链接的表,并寻找一种最优雅的方法。我的主要问题是,并不是所有的表行都提供了该链接。如果链接存在,我需要呈现"a"标记。如果没有-根本不需要"a"标签。一般来说,我想根据这个状态来处理这个选择(渲染与不渲染)。

这就是我现在所拥有的。

React.createClass({
    getInitialState: function () {
        return {
            pipeline: this.props.data.pipeline,
            liveUrl: this.props.data.liveUrl,
            posted: this.props.data.created,
            expires: this.props.data.end
        };
    },
    render: function () {
        return (
            <tr className="posting-list">
                <td><a href={this.state.liveUrl} target="_blank">{this.state.pipeline}</a></td>
                <td>Posted</td>
                <td>
                    <input className="datepicker" type="text" value={this.state.posted}/>
                </td>
                <td>
                    <input className="datepicker" type="text" value={this.state.expires}/>
                </td>
                <td>UPDATE, DELETE</td>
            </tr>
        );
    }
});

这个结果是DOM元素:

<a href="" target="_blank" data-reactid=".0.6.0.0.1:1.0.0">XING_batch</a>

这对我来说是不可接受的解决方案,因为那些空白的href仍然可以点击。我还尝试向getInitalState添加一些逻辑(liveUrl: (this.props.data.liveUrl !== "") ? this.props.data.liveUrl : "javascript:void;",),工作正常,但看起来很奇怪,并在控制台(Uncaught SyntaxError: Unexpected token ;)中添加了错误

我剩下的唯一方法是为

创建两个不同的组件

它只是JavaScript,所以你可以使用任何你喜欢的逻辑,例如:

<td>
    {this.state.liveUrl  
     ? <a ...>{this.state.pipeline}</a> 
     : this.state.pipeline}
</td>

您还可以在运行时选择组件的类型:

import * as React from "react";
const FooBar = props => {
  const Component = props.href ? "a" : "div";
  return (
    <Component href={href}>
      {props.children}
    </Component>
  );
};
<FooBar>Hello</FooBar> // <div>Hello</div>
<FooBar href="/">World</FooBar> // <a href="/">World</a>

查看排列属性:

你可以这样使用它们,例如:

var extras = { };
if (this.state.liveUrl) { extras.href = this.state.liveUrl; }
return <a {...extras} >My link</a>;

这些值将与直接设置的特性合并。如果它们不在对象上,则会被排除在外。