简体   繁体   English

反应-通过回调更改child1的道具并将新值传递给child2

[英]React - change props at child1 with callback and pass new value to child2

In my app I have a child component, 'Menu', where a 'select' state is updated by a click event, like so: 在我的应用程序中,我有一个子组件“菜单”,其中的“选择”状态通过点击事件进行更新,如下所示:

Menus.jsx (child): Menus.jsx (子项):

import React, { Component } from 'react';
import { Redirect } from 'react-router-dom';
import Brewing from './Brewing.jsx';
import { withRouter } from 'react-router-dom';


class Menus extends Component{
  constructor (props) {
    super(props);
    this.state = { 
        select: '',      
        isLoading: false,
        redirect: false
    };
  };

  (...)

  gotoCoffee = (index) => {
    this.setState({isLoading:true, select:this.state.coffees[index]})
    setTimeout(()=>{
      this.setState({isLoading:false,redirect:true})
    },5000)
    console.log(this.state.coffees[index])
  }

  renderCoffee = () => {
    if (this.state.redirect) {
      return (<Redirect to={'/coffee/'+this.state.select} />)
    }
  }

  render(){
    const coffees = this.state.coffees;

    return (
      <div>
        <h1 className="title is-1"><font color="#C86428">Menu</font></h1>
        <hr/><br/>
        {coffees.map((coffee, index) => 
          <span key={coffee}>
            <div>
               {this.state.isLoading && <Brewing/>}
               {this.renderCoffee()}
              <div onClick={() => this.gotoCoffee(index)} 
                   style={{textDecoration:'underline',cursor:'pointer'}}>
                  <strong><font color="#C86428">{coffee}</font></strong></div>
              <div>
              </div>
            </div>
          </span>)
        }
      </div>
    );
  }
}

export default withRouter(Menus);

the above works. 以上作品。


However, let's say I have another child component, 'Coffee', which should inherit this changed state. 但是,假设我有另一个子组件“ Coffee”,它应该继承此更改的状态。

I have learned that passing this event change, and state, from child to another child component, is an anti-pattern. 我了解到,将此事件更改和状态从子级传递到另一个子级组件是一种反模式。 Considering the ways of React, data can only flow from top-to-bottom ie, from parent-to-child. 考虑到React的方式,数据只能从上到下,即从父级到子级流动。

So have I tried to manage 'select' state from top to bottom, like so: 因此,我尝试从上至下管理“选择”状态,如下所示:

App.jsx (parent) App.jsx (父级)

class App extends Component {
  constructor() {
    super();
    this.state = {
      select: '',
    };
    this.onSelectChange = this.onSelectChange.bind(this);
  };

then I would use a callback here at 'App.jsx', like so: 那么我将在'App.jsx'处使用回调,如下所示:

onSelectChange(newSelect){ 
    this.setState({ select: newSelect });
  }

and pass it to 'Menus' component, like so: 并将其传递给“菜单”组件,如下所示:

<Route exact path='/menus' render={() => (
                    <Menus
                      onSelectChange={this.onSelectChange}
                    />
                  )} />

finally, at child 'Menus', I would user event change to change props, which could be passed to other childs etc: 最后,在子菜单“ Menus”中,我将使用用户事件更改来更改道具,这些道具可以传递给其他子项,例如:

gotoCoffee = (index) => {
    this.setState({isLoading:true})
    this.props.onSelectChange(index)
    setTimeout(()=>{
      this.setState({isLoading:false,redirect:true})
    },5000)
    console.log(this.props.select)
  }

but I'm getting console.log(this.props.select) 'undefined'. 但是我正在获得console.log(this.props.select) 'undefined'。

what am I missing? 我想念什么?

You are only passing onSelectChange method as a prop to Menu component right now, to access this.props.select, you need to pass select as prop to Menu. 您现在仅将onSelectChange方法作为prop传递给Menu组件,要访问this.props.select,您需要将select作为prop传递给Menu。

<Route exact path='/menus' render={() => (
  <Menus
    onSelectChange={this.onSelectChange}
    select={this.state.select}
  />
)} />

Whenever this.onSelectChange method gets called and state changes in your App.jsx, your Menu component will be rendered. 每当this.onSelectChange方法被调用并在App.jsx中更改状态时,就会呈现Menu组件。 You can use the updated this.props.select in your render method or in any non static method of your Menu component. 您可以在渲染方法或菜单组件的任何非静态方法中使用更新的this.props.select

class Menu extends Component {

  render() {
    console.log(this.props.select);

    return (
      ...
    );

  }
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM