如何获取Material UI中Typography组件渲染的值并将其赋值给React状态?
解决Material UI Typography组件值存入React状态的问题
嗨,我来帮你搞定这个问题~首先得明确核心问题:Material UI的Typography是纯展示型组件,它没有value属性,也不会触发onChange这类表单组件的事件,这就是你之前的代码无法生效的关键原因。
根据你的需求,分两种常见场景给你解决方案:
场景1:点击某个Typography时,将其对应的item.name存入state
直接给Typography绑定onClick事件就好,不需要通过事件对象取值——因为我们已经能直接拿到item.name:
import { useState } from 'react'; import Typography from '@mui/material/Typography'; const YourComponent = ({ array }) => { const [data, setData] = useState(''); return ( <div> {array.map((item, id) => ( <Typography key={id} onClick={() => setData(item.name)} style={{ cursor: 'pointer' }} // 可选,给文本加鼠标指针提示,提升交互感 > {item.name} {/* Typography的内容是通过子元素传递的,不是value属性哦 */} </Typography> ))} {/* 可以额外展示当前选中的值 */} <Typography variant="body2" color="text.secondary"> 当前选中:{data} </Typography> </div> ); };
这里要纠正你之前的一个小错误:value={item.name}是无效的,Typography组件不支持这个props,展示文本的正确方式是把内容放在组件标签内部。
场景2:把所有item.name的集合存入state
如果你的需求是一次性把数组里所有的item.name都存入state,不需要点击操作,那可以用useEffect监听数组变化,直接处理后赋值:
import { useState, useEffect } from 'react'; import Typography from '@mui/material/Typography'; const YourComponent = ({ array }) => { const [data, setData] = useState([]); // 当array变化时,自动更新data状态 useEffect(() => { const allNames = array.map(item => item.name); setData(allNames); }, [array]); return ( <div> {array.map((item, id) => ( <Typography key={id}> {item.name} </Typography> ))} {/* 展示所有存入state的名字 */} <Typography variant="body2" color="text.secondary"> 所有名字:{data.join(', ')} </Typography> </div> ); };
内容的提问来源于stack exchange,提问作者Brian
相关产品推荐
相关产品推荐

