reactjs - 在渲染方法中创建条件时不显示芯片按钮
问题描述
我正在尝试根据是否单击来呈现特定的芯片按钮。为此,我在包含所有按钮属性的组件状态上设置了一个变量。但是,我在 render 方法中的 if 语句没有显示按钮。但是,当我将它放在 if 语句之外时,它可以工作。
列状态变量的每个元素,是一个芯片按键状态
为了让它工作,我在 render() 上使用了这段代码:
{
this.state.columns.find(item => {
if (item.id === '1'){
return item.show === true ? (
<Grid item className={classes.chipWrapper}>
<Chip
label='Chip 1'
color="secondary"
deleteIcon={<DoneIcon />}
id='1'
onClick={this.handleChip}
/>
</Grid>
) : (
<Grid item className={classes.chipWrapper}>
<Chip
label='Chip 1'
color="secondary"
deleteIcon={<DoneIcon />}
id='1'
onClick={this.handleChip}
/>
</Grid>
)
}
})
}
这就是我在其余代码中的内容:
class ChipFilter extends React.Component {
state = {
anchorEl: null,
columns: [
{id: "1", show: false}
]
};
//simply change the property "show" of the column chosen
handleChip = (e) => {
this.setState(prevState => ({
columns: prevState.columns.map(
obj => (obj._id === e.currentTarget.id ? Object.assign(obj, { show: true }) : obj)
)
}));
}
无论显示属性如何,我都希望芯片按钮显示在屏幕上,但是材质 ui 应用了不同的设计风格。如果 show 为true,则芯片按钮的显示方式与为false时不同。现在它没有显示芯片按钮。
解决方案
您在渲染中使用 find 的方式不正确。Find 只是返回满足条件的项目。
例如
var found = items.find(function(item) {
return item > 10;
})
改用地图
this.state.columns.map(item => {
if (item.id === '1'){
return (<div> Inside </div>)
}
})
推荐阅读
- azure-logic-apps - 如何实现将文件从共享点提取到 blob 或 adls gen2 的解决方案
- apache-kafka - Apache Flink - 将流与输入 Kafka 主题同等分区
- github - Github actions/cache@v2: unrecognized option: posix in post job
- python - 熊猫数据框:找到平均年龄样本的平均体重,按性别分组
- swift - 带有 React-Native 的 Xcode Widget Extension 如何正确设置 @main
- javascript - DiscordJS / Canvas - 图像未从 URL 加载
- android - 应用已在 Play 商店发布但无法连接到 Admob
- javascript - 通过 chrome 扩展访问 Spring Secured API
- sql - 显示有条件的连续数据的 SELECT 语句
- java - Web 应用程序的 Java Oracle 数据库更改通知问题