React MaterialUI Card:如何在扩展时更改Card的类? ->自定义React组件 [英] React MaterialUI Card: how to change Card's class on expand? -> Custom React component

查看:86
本文介绍了React MaterialUI Card:如何在扩展时更改Card的类? ->自定义React组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

页面上有20张卡片.
MaterialUI卡具有onExpandChange属性,可以在其中定义如下操作:

There are 20 cards on the page.
MaterialUI Card has onExpandChange property where I can define an action like this:

<Card expandable={true} onExpandChange={this.clickHandle}>

在此操作中,我很容易知道所单击的卡是否已展开,因为在MaterialUI中,回调函数的定义如下:function(newExpandedState: boolean) => void

In this action I can easily know if the clicked card is expanded or not, because the callback function is defined like this in the MaterialUI: function(newExpandedState: boolean) => void

clickHandle = (newExpandedState: boolean) => {
    //do something
}

现在,我想更改卡的类别,例如,当newExpandedStatetrue时,将其赋予类别expanded.

Now I would like to change card's class, for example, give it class expanded when newExpandedState is true.

问题,我不知道如何告诉该功能哪个卡已扩展.像onExpandChange={this.clickHandle(newState, 'card1')}之类的东西不起作用.我的页面上有20张卡片,但我不知道哪一张应该获得expanded类.任何想法如何做到这一点?

The problem is that I don't know how to tell this function which card has been expanded. Things like onExpandChange={this.clickHandle(newState, 'card1')} don't work. I have 20 cards on the page and I don't know which one should get expanded class. Any ideas how to do this?

推荐答案

一种方法是用您自己的自定义卡片包装材料UI卡片,并为其添加状态: 从'react'导入React; 从"material-ui"导入{Card};

One way to do it is to wrap the material-ui's card with your own custom card and add a state to it: import React from 'react'; import { Card } from 'material-ui';

class MyCustomCard extends React.Component {
  state = {
    expanded: null
  }

  toggleExpanded = () => {
    this.setState((state) => ({
      expanded: !state.expanded
    }))
  }

  render() {
    return <Card expandable expanded={this.state.expanded} onExpandChange={this.toggleExpanded}>
  }
}

然后您可以像这样使用它:

Then you can use it like this:

import React from 'react';
import Card from '../MyCustomCard';

class App extends React.Component {
  ...

  render() {
    return (
      <div>
        <Card />
        <Card />
        <Card />
        <Card />
        <Card />
        ...
      </div>
    )
  }
}

这篇关于React MaterialUI Card:如何在扩展时更改Card的类? -&gt;自定义React组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆