React MaterialUI Card:如何在扩展时更改Card的类? ->自定义React组件 [英] React MaterialUI Card: how to change Card's class on expand? -> Custom React component
问题描述
页面上有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
}
现在,我想更改卡的类别,例如,当newExpandedState
为true
时,将其赋予类别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的类? ->自定义React组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!