如何基于react-select的OnChange事件在JSX中动态展示对应元素
代码问题与修复方案
你代码里的核心问题如下:
- 事件处理函数中返回的JSX不会被渲染到页面,所有需要渲染的内容必须放在组件的return语句范围内
- setState是异步更新逻辑,执行
setTableValue(true)后立刻读取tableValue拿到的还是更新前的旧值,判断逻辑永远不生效 Array.filter返回的是数组,直接渲染数组会触发异常,你需要的是匹配结果的长度,要加.length- react-select的onChange回调返回的是选中项对象,你需要在渲染阶段根据选中值动态计算要展示的内容,而不是在事件回调里处理渲染逻辑
修正后完整代码
import React, { useContext, useState } from 'react' import styles from './FullRecord.module.css' import {AuthContext} from '../../shared/context/auth-context' import Select from 'react-select' import { makeStyles } from '@material-ui/core/styles'; import Card from '@material-ui/core/Card'; import CardContent from '@material-ui/core/CardContent'; import Typography from '@material-ui/core/Typography'; const useStyles = makeStyles({ custom: { backgroundColor: "#558d6b", fontWeight: "bold" }, customFont: { fontWeight: "bold", fontSize: "20px" }, customFont1: { fontWeight: "light" } }); const FullRecord = (props) => { const auth = useContext(AuthContext) const classes = useStyles(); const [selectedValue, setSelectedValue] = useState(null); const options = auth.tournaments.map((tournament) => { return { value: tournament.TournamentName, label: tournament.TournamentName, } }) const handleChange = (selectedOption) => { setSelectedValue(selectedOption); } // 渲染阶段计算要展示的比赛数量 const renderMatchCount = () => { if(!selectedValue) return null; const {value} = selectedValue; if(value === 'GSM Edition 1'){ const noOfMatches = auth.profile.MemberMatches.filter((match) => match.TournamentName === 'GSM Edition 1').length; return ( <div> <li className={styles['member-item']}> <Card className={classes.custom} variant="outlined"> <CardContent> <Typography className={classes.customFont} gutterBottom> Number Of Matches Played </Typography> <Typography className={classes.customFont}> {noOfMatches} </Typography> </CardContent> </Card> </li> </div> ) } // 可在此处扩展其他选项对应的渲染逻辑 return null; } return ( <React.Fragment> <div className={styles['fullrecord__maindiv']}> <Select onChange={handleChange} options={options} value={selectedValue} /> {/* 插入动态渲染的内容 */} {renderMatchCount()} </div> </React.Fragment> ) } export default FullRecord
内容的提问来源于stack exchange,提问作者Sandy
相关产品推荐
相关产品推荐

