渲染”;a“;React.js中的可选href
Rendering "a" with optional href in React.js
我需要在其中一列中呈现一个带有链接的表,并寻找一种最优雅的方法。我的主要问题是,并不是所有的表行都提供了该链接。如果链接存在,我需要呈现"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>;
这些值将与直接设置的特性合并。如果它们不在对象上,则会被排除在外。
相关文章:
- React重新渲染但未显示正确的组件
- 在单击href链接的同时下载文件
- React组件等待所需道具进行渲染
- React中的数据集表示
- Webpack开发服务器和React服务器端渲染
- 如果href包含X,请更改href
- 锚点元素的href属性自动更改
- 锚点元素不't使用svg时,请打开EDGE上的href
- React Redux错误页面管理
- 检测电话窃听,即:<a href="电话:xxx">在UIWebview上
- react.js中的密钥绑定
- 如何覆盖锚点元素's href目标,并在我点击转到目标javascript时删除其他错误
- 如何在react js中将值从一个组件发送到另一个组件
- React Native通过Navigator将用户输入数据传递到选项卡栏IOS中的组件
- React:按键的性能提升
- 如何在react js中从一个页面导航到另一个页面
- 渲染”;a“;React.js中的可选href
- React路由器<link>如何在Jest测试中获取href的值
- 动态 href 标签 React in JSX.
- Testing React-Router v1.0.0 href