typ*_*pos 2 javascript reactjs material-ui
我在一个项目中使用 Material UI 和 React,我有一个组件,大致如下所示:
import React, { Component } from 'react';
import { List, ListItem } from 'material-ui';
import PropTypes from 'prop-types';
class MyComp extends Component {
constructor(props) {
super(props);
this.onClickMethod = this.onClickMethod.bind(this);
}
onClickMethod() {
// removed for brevity
}
render() {
return (
<div>
<List>
{this.props.myData.map(pp => {
return (
<ListItem key={pp.name}
style={styles.listItem}
primaryText={pp.name}
onClick={this.onClickMethod}
/>
)
})}
</List>
</div>
);
}
}
const styles = {
listItem: {
// removed for brevity, includes some styles
},
listItemClicked: {
// removed for brevity, includes different styles than the ones in listItem
},
};
MyComp.propTypes = {
myData: PropTypes.array.isRequired,
};
export default MyComp;
Run Code Online (Sandbox Code Playgroud)
现在的重点是,我最初希望所有 ListItem 都具有相同的样式,即styles.listItem
对象属性内的样式。然后,如果用户单击某个 ListItem,我希望其样式更改为styles.listItemClicked
对象属性内的样式。但是,其余未单击的 ListItem 不应更改其样式。此外,如果用户已经单击了一个 ListItem 并决定单击另一个 ListItem,那么我希望之前单击的 ListItem 将其样式更改为内部的默认样式,styles.listItem
并使用新单击的 ListItem 来获取styles.listItemClicked
样式。因此,在任何时候,只有零(最初)或其中一个 ListItem 具有styles.listItemClicked
. 任何想法如何在 React 中实现这一点?
维护一个包含被点击的 listItem 索引的状态,并使用一个简单的条件来改变该特定项目的样式,如下所示
class MyComp extends Component {
constructor(props) {
super(props);
// Initialize a state which contain the index of clicked element (initially -1)
this.state = { indexOfClickedItem: -1};
this.onClickMethod = this.onClickMethod.bind(this);
}
onClickMethod(index) {
// removed for brevity
// When clicked then set the state with the index of clicked item
this.setState({indexOfClickedItem: index});
}
render() {
return (
<div>
<List>
{this.props.myData.map((pp,index) => {
return (
<ListItem key={pp.name}
// Use simple condition to change the style of clicked element
style={this.state.indexOfClickedItem === index ? styles.listItemClicked : styles.listItem}
primaryText={pp.name}
onClick={this.onClickMethod.bind(this,index)}
/>
)
})}
</List>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1056 次 |
最近记录: |