Reactjs: Passing props from card component to tab

2019-08-15 14:18发布

问题:

  • i am new to react.
  • I am trying to pass the props from the child component to the parent component tabs which has favourites tabs.
  • so i thought I will pass the values from handleClickOpen method, since thats where I click the favoutites icon.
  • but not sure how to pass.
  • when I click the favourites in the cards component it should get saved in the favourites tab.
  • can you tell me how to fix it, so that in future I will fix it myself.
  • since passing the props is important concept.
  • all my code is in tab-demo.js

https://codesandbox.io/s/40mmrl9059

 <CardActions className={classes.actions} disableActionSpacing>
                    <IconButton
                      onClick={this.handleClickOpen}
                      aria-label="Add to favorites"
                    >
                      <FavoriteIcon />
                    </IconButton>

     <AppBar position="static" color="default">
          <Tabs
            value={value}
            onChange={this.handleChange}
            scrollable
            scrollButtons="on"
            indicatorColor="primary"
            textColor="primary"
          >
            <Tab label="Search" icon={<PhoneIcon />} />
            <Tab label="Favorites" icon={<FavoriteIcon />} />
            {/* <Tab label="Item Three" icon={<PersonPinIcon />} />
            <Tab label="Item Four" icon={<HelpIcon />} />
            <Tab label="Item Five" icon={<ShoppingBasket />} />
            <Tab label="Item Six" icon={<ThumbDown />} />
            <Tab label="Item Seven" icon={<ThumbUp />} /> */}
          </Tabs>
        </AppBar>

react code

 handleClickOpen = currentTarget => {
    console.log("handleClickOpen--->");
    console.log("event.currentTarget--->", currentTarget.relatedTarget);
    // console.log("event.relatedTarget--->", relatedTarget);

    // this.setState({ open: true });
  };

TabContainer.propTypes = {
  children: PropTypes.node.isRequired
};

function TabsFavourites(props) {
  return (
    <Typography component="div" style={{ padding: 8 * 3 }}>
      {props.children}
    </Typography>
  );
}

TabsFavourites.propTypes = {
  children: PropTypes.node.isRequired
};

回答1:

Example:

You have structure:

<Parent>
  <Tabs />
  <Child />
</Parent>

Then your Parent component should be as below. You pass new added favorites as props downward to Tabs. You add new favorites updating the parent state.

class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      favorites: []
    }
    this.handleClick = this.handleClick.bind(this);
  }

  // props
  handleClick(prop) {
    this.setState({ favorites: this.state.concat(prop) })
  }

  render() {
    const { favorites } = this.state;
    return (
      <div>
        <Tabs favorites={ favorites } />
        <Child onClick={ this.handleClick }/>
      </div>
    )
  }
}