程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了React:如何通过来自 react-router-dom 的链接传递道具?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决React:如何通过来自 react-router-dom 的链接传递道具??

开发过程中遇到React:如何通过来自 react-router-dom 的链接传递道具?的问题如何解决?下面主要结合日常开发的经验,给出你关于React:如何通过来自 react-router-dom 的链接传递道具?的解决方法建议,希望对你解决React:如何通过来自 react-router-dom 的链接传递道具?有所启发或帮助;

我正在尝试使用 Titledishes 从 props 传递到我的 <link> 组件,但找不到解决方案。有什么建议吗?

import { link } from "react-router-dom";

const category = ({ Title }) => {
  return (
    <link to="/dishes">
      {Title}
    </link>
  );
};

export default category;

App.Js 看起来像这样:

return (
    <Router>
      <div classname="App">
        <Route
          path="/"
          exact
          render={(props) => (
              <CategorIEs recipes={recipes} />
          )}
        />
        <Route path="/dishes" component={dishes} />
      </div>
    </Router>
  );

解决方法

Link 可以传递一个状态对象,该对象可以通过位置从您的组件中检索:

import { Link } from "react-router-dom";

const Category = ({ title }) => {
  return (
    <Link to={{ pathname: "/dishes",state: { title } }}>
      {title}
    </Link>
  );
};

export default Category;

然后您可以从 state 属性中提取 location。但由于您仅在单击 Link 时传递此值,因此如果您直接访问 stateRoute 可以未定义。通过这种方式,您可能希望在这些情况下提供 defaultValue

const Dishes = ({location}) => {
  const { title = 'defaultValue' } = location.state || {}

  return <div>{title}</div>
}

大佬总结

以上是大佬教程为你收集整理的React:如何通过来自 react-router-dom 的链接传递道具?全部内容,希望文章能够帮你解决React:如何通过来自 react-router-dom 的链接传递道具?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: