hit*_*ker 2 javascript reactjs react-router
我正在编写一个React.js应用程序,我想在其中使用Linkreact-router 包中的组件,以便有条件地将用户重定向到另一个页面。如果某些条件不成立,我将to道具设置为空字符串,该字符串有效并且不会导致页面重新加载并且页面保持在与原来完全相同的位置。但我想知道这是否是最佳实践?
这是我的解决方案:
import { Link } from 'react-router';
<Link to={condition === true ? '/some/other/url' : ''}>
<div>
my content
</div>
</Link>
Run Code Online (Sandbox Code Playgroud)
我在文档中没有看到有关空字符串输入的任何内容。
我从来没有在 HTML 或 React 中将任何东西与任何东西联系起来。也就是说,您似乎只有几个选择:
选项 1
有条件地呈现div非to属性。如果 codition 是 true 显示Linkdiv 如果不显示 div 没有Link。这可能是更“常见”的方式来做到这一点。如果您div不像“我的内容”那么简单,我会将其移至功能组件中。并使用该组件而不是<div>MyContent</div>如下所示。
import { Link } from 'react-router';
{ condition ?
(
<Link to='/some/other/url'>
<div>My Content</div>
</Link>
) : ( <div>My Content</div> )
}
Run Code Online (Sandbox Code Playgroud)
选项 2
执行您所做的操作,但使用#代替 空字符串。
import { Link } from 'react-router';
<Link to={condition === true ? '/some/other/url' : '#'}>
<div>
my content
</div>
</Link>
Run Code Online (Sandbox Code Playgroud)
选项 3如果条件为假,则禁用链接。
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>
Run Code Online (Sandbox Code Playgroud)
希望有帮助。
| 归档时间: |
|
| 查看次数: |
3045 次 |
| 最近记录: |