【问题标题】:How to use ternary operator using react with route?如何使用与路由反应的三元运算符?
【发布时间】:2020-07-20 13:02:06
【问题描述】:

我想通过 react 使用三元运算符和路由。

我想做什么? 以下是条件:

(条件1或条件2为真)并且用户在除“items/:itemId”之外的任何url中显示child1组件

(condition1 或 condition2 为 true )且用户仅在 url "/items/:itemId" 显示 child1 和其他组件

belwo 是当 route 为任何且 condition1 或 condition2 为真时显示 Child1 组件的 sn-p

function Parent () {
    return (
        {(condition1 || condition2) &&
            <Child1/>
        )}
    );
}

当条件1或条件2为真且路径仅为“/items/:itemId”时,我想显示child1和另一个组件

我尝试了什么?

function Parent () {
    return (
        {(condition1 || condition2) &&
            <Child1 onHide={on_hide}/>
        )}
        <Route
            path="/items/:itemId"
            render={routeProps =>
                condition1 || condition2 ? (
                    <>
                        <Child1 {...routeProps} onHide={on_hide}/>
                        <Another />
                    </>
                ) : null
            }
        />

interface Props {
    onHide: any;
}

function child1 ({ onHide }: Props) {
    //somelogic
}

但这根本不会渲染任何东西。意思是不满足任何条件。有人可以帮我解决这个问题吗?谢谢。

【问题讨论】:

  • 您能否提供有关您的条件的任何详细信息?
  • 在其中一个条件为 true 的情况下尝试您的代码
  • 当我从代码中删除 Route 的东西时它可以工作......
  • @nir shabi: 我已经清楚地更新了条件
  • 也许我在 child1 组件中缺少使用 routeprops 我应该如何将 routeprops 传递给 child1 组件。更新 child1 组件

标签: reactjs


【解决方案1】:

你不应该尝试像这样使用 react 路由器渲染两个组件。而是创建另一个组件,其中包含所有需要的组件。

例如(使用 es6):

import React from 'react';
import { withRouter, matchPath } from 'react-router-dom';

const Wrapper = (props) => {
  const renderComponent = () => {
    if (matchPath(props.location.pathname == '/items/:itemId') {
      return (
       <>
        <Child1 {...props.routeProps} onHide={props.on_hide}/>
        <Another />
       </>
      )
    } else {
      return <Child1 {...props.routeProps} onHide={props.on_hide}/>
    }
  }
  return renderComponent();
};

export default withRouter(Wrapper);

在你的路由组件中你可以这样做:

 {condition1 || condition2 ? (
   <Route
     path="/"
     render={(routeProps) => (
       <Wrapper {...routeProps} onHide={on_hide} />
     )}
   />
 ) : null}

【讨论】:

    猜你喜欢
    • 2018-11-19
    • 1970-01-01
    • 2018-04-11
    • 2019-07-19
    • 2022-11-15
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    相关资源
    最近更新 更多