[英]React MaterialUI Card: how to change Card's class on expand? -> Custom React component
頁面上有20張卡片。
MaterialUI卡具有onExpandChange
屬性,可以在其中定義如下操作:
<Card expandable={true} onExpandChange={this.clickHandle}>
在此操作中,我很容易知道所單擊的卡是否已展開,因為回調函數在MaterialUI中是這樣定義的: function(newExpandedState: boolean) => void
clickHandle = (newExpandedState: boolean) => {
//do something
}
現在,我想更改card的類,例如,當newExpandedState
為true
時,將其expanded
為class。
問題是我不知道如何告訴該功能哪個卡已擴展。 諸如onExpandChange={this.clickHandle(newState, 'card1')}
不起作用。 我的頁面上有20張卡片,但我不知道應該expanded
哪張卡片。 任何想法如何做到這一點?
你可以這樣做:
1.維護一個state
變量array
,該array
將記錄處於擴展狀態的卡的所有ID(卡的任何唯一屬性)。
constructor(){
super();
this.state = {
cardStatus: []
}
}
2.將唯一值傳遞給每個onExpandChange
方法:
onExpandChange={() => this.clickHandle(card.name)}
3.現在,如果newExpandedState
為true
,則在state array
推送該值,否則將其刪除:
clickHandle(name, newExpandedState){
let cardStatus = this.state.cardStatus.slice();
if(newExpandedState)
cardStatus.push(name);
else{
let index = this.state.cardStatus.indexOf(name);
cardStatus.splice(index,1);
}
this.setState({cardStatus});
}
4.現在,在生成卡時,檢查cardStatus array
是否具有card的唯一屬性,然后應用不同的classNames
。
<Card className={this.state.cardStatus.indexOf(card.name) >= 0 ? 'expanded': 'not'}>
一種方法是用您自己的自定義卡包裝Material-ui的卡,並為其添加狀態:從“ react”導入React; 從“ material-ui”導入{Card};
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}>
}
}
然后,您可以像這樣使用它:
import React from 'react';
import Card from '../MyCustomCard';
class App extends React.Component {
...
render() {
return (
<div>
<Card />
<Card />
<Card />
<Card />
<Card />
...
</div>
)
}
}
只是分享結果:
最終在@ glenn-reyers的幫助下使其工作,並為CustomCard組件獲得了以下代碼:
import React from 'react';
import {Card} from 'material-ui/Card';
class CustomCard extends React.Component<any, any> {
state = {
expanded: false
}
handleExpandChange = (expanded) => {
this.setState({expanded: expanded});
};
render() {
return
<Card
className={this.state.expanded ? 'controller-card expanded' : 'controller-card'}
expandable={true}
expanded={this.state.expanded}
onExpandChange={this.handleExpandChange}>
{this.props.children}
</Card>
}
}
export default CustomCard;
工作小提琴在這里: https : //codesandbox.io/s/76O8pnW9Q
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.