React中为特定记录字段修改CSS类的问题
解决特定输入框高亮问题
你当前的问题在于changed状态是一个简单字符串,所有绑定了className={changed}的输入框都会在任意输入修改时被高亮。要实现仅高亮当前编辑的输入框,需要跟踪具体是哪条数据的哪个字段被修改,具体调整如下:
- 修改状态结构:将
changed从字符串改为对象,存储当前编辑的条目ID和字段名 - 更新事件处理逻辑:在输入变更时记录对应的ID和字段名
- 条件绑定高亮类:每个输入框根据自身的ID和字段名是否匹配状态值,决定是否应用高亮类
修改后的完整代码
function AppCookie() { const [cookies, setCookies] = useState(); // 改为存储id和字段名的对象,初始值为空状态 const [changed, setChanged] = useState({ id: null, field: '' }); const onChangeInput = (e, id) => { const { name, value } = e.target; // 记录当前编辑的id和对应字段名 setChanged({ id, field: name }); const editData = cookies.map((cookie) => cookie.id === id ? { ...cookie, [name]: value } : cookie ); setCookies(editData); }; const handleClick = async (event) => { ... }; useEffect(() => { populateCookieData(); }, []); const contents = cookies === undefined ? <p><em>Loading...</em></p> : ( <table className="table table-striped" aria-labelledby="tabelLabel"> <thead> <tr> <th>Id</th> <th>Date</th> <th>Name</th> <th>Desc</th> <th>Price</th> </tr> </thead> <tbody> {cookies.map(cookie => ( <tr key={cookie.id}> <td>{cookie.id}</td> <td>{cookie.date}</td> <td> <input name="name" value={cookie.name} type="text" onChange={(e) => onChangeInput(e, cookie.id)} placeholder="Type Name" // 条件判断是否应用高亮类 className={changed.id === cookie.id && changed.field === 'name' ? 'highlighted-input' : ''} /> </td> <td> <input name="desc" value={cookie.desc} type="text" onChange={(e) => onChangeInput(e, cookie.id)} placeholder="Type Desc" className={changed.id === cookie.id && changed.field === 'desc' ? 'highlighted-input' : ''} /> </td> <td> <input name="price" value={cookie.price} type="text" onChange={(e) => onChangeInput(e, cookie.id)} placeholder="Type Price" className={changed.id === cookie.id && changed.field === 'price' ? 'highlighted-input' : ''} /> </td> <td> <button type="submit" onClick={() => handleClick({ cookie })}>Update</button> </td> </tr> ))} </tbody> </table> ); return ( <div> <h1 id="tabelLabel">Cookies</h1> {contents} </div> ); async function populateCookieData() { ... } }
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

