我正在写一个React.js http://React%20%E2%80%93%20A%20JavaScript%20library%20for%20building%20user%20interfaces%20%20https://reactjs.org/我想使用的应用程序Link
来自react-router包的组件,以便有条件地将用户重定向到另一个页面。如果某些条件不成立,我设置to
prop 为空字符串,该字符串有效且不会导致页面重新加载,并且页面保留在原来的位置。但我想知道这是否是最佳实践?
这是我的解决方案:
import { Link } from 'react-router';
<Link to={condition === true ? '/some/other/url' : ''}>
<div>
my content
</div>
</Link>
我没有看到任何内容文档 https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/api/Link.md关于空字符串输入。
我从来没有在 HTML 或 React 中将某些东西与任何东西联系起来。也就是说,你似乎没有什么选择:
Option 1有条件地渲染div
不是to
属性。如果条件为真则显示Link
如果没有则显示 div,如果没有则显示 divLink
。这可能是更“常见”的方法。如果你的div
并不像“我的内容”那么简单,我会将其移至功能组件中。并使用该组件而不是<div>MyContent</div>
如下所示。
import { Link } from 'react-router';
{ condition ?
(
<Link to='/some/other/url'>
<div>My Content</div>
</Link>
) : ( <div>My Content</div> )
}
Option 2做你所做的但使用#
而不是空字符串。
import { Link } from 'react-router';
<Link to={condition === true ? '/some/other/url' : '#'}>
<div>
my content
</div>
</Link>
Option 3如果条件为 false,则禁用链接。
import { Link } from 'react-router';
//a better name might be in order here
const handleLinkDisable = (e) => {
const { condition } = this.state; //just assuming it comes from state
if(condition){ e.preventDefault(); }
};
<Link to='/some/other/url' onClick={handleLinkDisable}>
<div>My Content</div>
</Link>
希望有帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)