1

这是我的目标。我想创建一个复合组件,它将在显示children元素之前检查匹配 url 的有效性。否则,它会返回一个通用组件以显示错误消息。

所以这是我的“装饰器”代码:

const EnforceUrlValidation = (test, children) => {
  const fn = ({ match }) => {
    if (! test( match )) {
      return ( <InvalidUrlContainer /> );
    }
    return ({children});
  }
  return fn;
}

这是它在我的路由器中的使用方式:

const WelcomePage = EnforceUrlValidation(
    (match) => {
      const articleId = match.params.articleId;
      return articleId && isValidarticleId(articleId);
    }
  , <WelcomeContainer/>
)
...
<Routers>
     <Switch>
          <Route
              path="/:articleId"
              component={WelcomePage}
           />
...

</Routers>

我现在遇到的问题是我仍然想将match对象传递到childreninside EnforceUrlValidation。我怎样才能做到这一点?

尝试 1

const EnforceUrlValidation = (test, children) => {
  const fn = ({ match }) => {
    if (! test( match )) {
      return ( <InvalidUrlContainer /> );
    }
    return (<children match={match} />);
  }
  return fn;
}

在这种children情况下不呈现。

尝试 2

const EnforceUrlValidation = (test, children) => {
  const fn = ({ match }) => {
    if (! test( match )) {
      return ( <InvalidUrlContainer /> );
    }
    return (
      <div match={match} >{children} </div>
    )
  }
  return fn;
}

失败是因为div不支持match

4

1 回答 1

7

您可以使用React.cloneElement将属性添加到孩子:

const EnforceUrlValidation = (test, children) => {
  const fn = ({ match }) => {
    if (! test( match )) {
      return ( <InvalidUrlContainer /> );
    }
    const extendedChild = React.cloneElement(children, {match: match});
    return extendedChild;
  }
  return fn;
}
于 2017-03-22T10:38:01.830 回答