简体   繁体   English

单击react-router Link时,如何将状态传输到父组件?

[英]How do I transmit a state to a parent component when clicking a react-router Link?

I want to build a single page application that works with transitions, that would look like follows: 我想构建一个与转换一起使用的单页面应用程序,如下所示:

*------*--------------*-----------*
|      |              |           |
| Shop | Landing Page | Biography |
|      |              |           |
*------*--------------*-----------*
|                                 |
|          Contact page           |
|                                 |
*---------------------------------*

Basically, when you first come on the website, you arrive on the landing screen. 基本上,当您第一次登陆网站时,您将到达登陆屏幕。 From there, 3 links are available, 'Biography', 'Shop' and 'Contact' ('Contact' is available from the three 'top' pages). 从那里可以获得3个链接,“传记”,“商店”和“联系”(“联系”可从三个“顶部”页面获得)。

Once you click on the link to go to either 'Shop' or 'Biography', you can go back to the landing or go to the contact page, but you can't go the the "opposite" page (hence the schema). 一旦您点击链接转到“商店”或“传记”,您就可以返回登陆或转到联系页面,但不能转到“对面”页面(因此是架构)。 Also, when you get to contact page and click 'back', you'll get to the last page you were before. 此外,当您联系页面并单击“返回”时,您将转到之前的最后一页。

I created a CodeSandBox to avoid pasting half a kilometer of code that don't necessarly have anything to do with this but are still a bit concerned 我创建了一个CodeSandBox,以避免粘贴半公里的代码,这些代码不一定与此有任何关系,但仍然有点担心

So I would like to be able to precisely setup my transitions, like going from left to right when going to 'Biography' (and the opposite when leaving), right to left when going to "Shop", and bottom to top when going to the contact form. 所以我希望能够精确地设置我的过渡,例如在进入“传记”时(从离开时相反的方向)从左到右,在去“商店”时从右到左,以及在去“购物”时从下到上联系表格。

After reading tons of issues and documentations about react-transition-group , I had the idea of doing something like this: 在阅读了大量有关react-transition-group的问题和文档之后,我有了这样的想法:

// src/App.js
const PageFade = props => (
  // props.transition would contain "topBottom", "bottomTop", "leftRight" and "rightLeft" 
  // (so that I would ajust my CSS in consequence)
  {props.transition === 'topBottom' &&
  <CSSTransition
    {...props}
    classNames={props.transition !== null && props.transition}
    timeout={1000}
    mountOnEnter={true}
    unmountOnExit={true}
  />
  }
);
}

I could do this or create a <CSSTransition /> for each possibility, I don't really know. 我可以这样做或为每种可能性创建一个<CSSTransition /> ,我真的不知道。

My problem is that I need to tell this <CSSTransition /> either what have been clicked or (better) what transition it needs to display. 我的问题是我需要告诉这个<CSSTransition />被点击的内容或(更好)需要显示的转换。

To do so, I tried to set a transition state, but it looks like it gets too much refreshed, and my knowledge of React is rusty, and I don't know how to handle all this with react-route. 为此,我试图设置一个transition状态,但看起来它刷新得太多了,而且我对React的了解是生锈的,我不知道如何使用react-route处理所有这些。

Update 更新

Thank you all for your answers, and sorry for not answering faster, my computer is freezing beyond madness. 谢谢大家的回答,抱歉没有快速回答,我的电脑已经疯狂了。

So I created a new class CSSTransitions where I copied / pasted @brandon's answer while adapting it to my needs. 所以我创建了一个新的CSSTransitions ,在这里我复制/粘贴@ brandon的答案,同时根据我的需要进行调整。 However, I have a problem with the componentWillReceiveProps(nextProps) , because it nextProps.location is null, somehow, the react-router's context isn't passed. 但是,我有一个componentWillReceiveProps(nextProps) ,因为它nextProps.location是null,不知何故,react-router的上下文没有被传递。

I updated my CodeSandBox, the CSSTransitions class is in an 'utils' directory inside the 'src' directory. 我更新了我的CodeSandBox, CSSTransitions类位于'src'目录下的'utils'目录中。

Thank you again for your answers 再次感谢您的回答

Thank you in advance 先感谢您

My suggestion is to just have your PageFade component monitor the routes and compare previous route to new route and change its direction based on the change in routes. 我的建议是让你的PageFade组件监控路由并将之前的路由与新路由进行比较,并根据路由的变化改变其方向。 Here's a rough example: 这是一个粗略的例子:

import {withRouter} from 'react-router';

const directions = {
  "/->/contact": "top-bottom",
  "/contact->/": "bottom-top",
  // etc...
}

class PageFadeDumb extends React.Component {
  state = {direction: "top-bottom"};

  componentWillReceiveProps(nextProps) {
    if (nextProps.location.pathname !== this.props.location.pathname) {
      const transitionPath = `${this.props.location.pathname}->${nextProps.location.pathname}`;
      const newDirection = directions[transitionPath] || "top-bottom";
      console.log(`newDirection = ${newDirection}`);
      this.setState({direction: newDirection});
    }
  }

  render() {
    const direction = this.state.direction;
    // use here somehow?
    return (
      <CSSTransition
        {...(this.props)}
        classNames="fadeTranslate"
        timeout={1000}
        mountOnEnter={true}
        unmountOnExit={true}
      />
    );
  }
}

const PageFade = withRouter(PageFadeDumb);

I would do it this way: 我会这样做:

class ParentComponent extends React.Component {

  state = {
    some_state: ""
  }

  myCallback = (ev) => {
    this.setState({ some_state: ev.target.dataset.mydata });
  }

  render() {
    <ChildComponent cback={this.myCallback} />  // Insert all other props too
  }

}

class ChildComponent extends React.Component {

  render() {
    <button data-mydata="Value you need to pass up" onClick={this.props.cback}>
      Click me
    </button>
  }

}

When the button is clicked the callback defined in ParentComponent is triggered and receives an Event object and then you may capture one or more values using data- attributes . 单击该按钮时,将触发ParentComponent定义的回调并接收Event对象 ,然后您可以使用data-attributes捕获一个或多个值。

To learn more about these data- attributes and HTMLElement.dataset you may read this . 要了解有关这些data-属性和HTMLElement.dataset更多信息,您可以阅读此内容

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在React.js的父组件中使用react-router时,如何使用react context API将数据从父组件传递到子组件? - How do I use react context API to pass data from parent component to child component when using react-router in the parent component in React.js? 如何使用 react-router 的链接组件链接到我的应用程序外部的 URL? - How do I link to a URL outside of my app using the Link component of react-router? 如何在react-router上的链接中引用状态 - How to refer state in link on react-router React-Router-父组件状态更改时组件重新加载? - React-router - component reloads on parent component state change? 隐藏菜单并在单击react-router链接时重定向 - Hide menu and redirect when clicking on react-router Link 在点击时,react-router 4不会更新UI <Link> - react-router 4 doesn't update UI when clicking <Link> 如何在使用React-Router&Redux时单击链接时调度操作? - How to dispatch an action when clicking on Link when using React-Router & Redux? 如何使用react-router将顶级组件状态传递给路由? - How do you pass top level component state down to Routes using react-router? 当登录状态处于组件状态时,如何使用 react-router 实现与登录相关的路径? - How to implement login-dependent paths with react-router, when the login-status is in the component-state? 如何从文本呈现 react-router Link 组件? - How to render a react-router Link component from text?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM