React表格行选中时className不更新且报错问题求助
问题分析与解决
你的代码里有两个核心问题导致className报错和样式不更新:
1. 静态方法中错误引用this
renderChildsTable是静态方法,它内部的this指向的是ChildTable类本身,而非组件实例,所以this.selectedRow会直接报错。而且你已经把selectedRow作为参数传入了这个方法,直接用参数即可,不需要用this。
2. 点击行时未正确更新组件状态
你在点击事件里直接给selectedRow变量赋值:selectedRow = children.id,这只是修改了局部变量,不会触发React的状态更新机制,组件不会重新渲染,样式类自然也不会变化。必须通过this.setState来更新状态,才能让组件重新渲染并应用新样式。
修改后的完整代码
import React, { Component } from "react"; import "../custom.css"; // 记得导入ButtonGroup,否则会报错 import { ButtonGroup } from 'react-bootstrap'; // 根据实际使用的UI库调整 export class ChildTable extends Component { constructor(props) { super(props); this.state = { childrens: [], loading: true, selectedRow: -1 }; // 绑定事件处理方法的this指向 this.handleRowClick = this.handleRowClick.bind(this); } componentDidMount() { this.Get(); } // 把静态方法改为实例方法,直接访问组件状态与方法 renderChildsTable() { const { childrens, selectedRow } = this.state; return ( <table className="table table-striped" aria-labelledby="tabelLabel"> <thead> <tr> <th>id</th> <th>Name</th> <th>Surname</th> </tr> </thead> <tbody> {childrens.map((children) => ( <tr key={children.id} onClick={() => this.handleRowClick(children.id)} className={`clickable-row ${selectedRow === children.id ? 'selected' : ''}`} > <td>{children.id}</td> <td>{children.name}</td> <td>{children.surname}</td> </tr> ))} </tbody> </table> ); } // 行点击处理方法,通过setState更新选中状态 handleRowClick(rowId) { this.setState({ selectedRow: rowId }); console.log(rowId); } render() { let contents = this.state.loading ? ( <p> <em>Loading...</em> </p> ) : ( this.renderChildsTable() ); return ( <div> <h1 id="tabelLabel">Таблица детей</h1> <p>This component demonstrates fetching data from the server.</p> <ButtonGroup></ButtonGroup> {contents} </div> ); } async Get() { const response = await fetch("api/Children"); const data = await response.json(); this.setState({ childrens: data, loading: false }); console.log(this.state.selectedRow); } } export default ChildTable;
关键改动说明
- 将
renderChildsTable从静态方法改为实例方法,直接访问组件的this.state和this.setState。 - 新增
handleRowClick方法,通过this.setState更新selectedRow状态,触发组件重新渲染。 - 使用模板字符串简化className写法,直接用
this.state.selectedRow做判断,避免之前的this引用错误。 - 绑定
handleRowClick的this到组件实例,确保事件回调中能正确调用this.setState。 - 补充
ButtonGroup的导入(如果项目未使用相关UI库,可删除该行)。
修改后,点击行时会正确更新选中状态,对应的selected样式类也会被添加到选中行上,不会再出现className相关报错。
内容的提问来源于stack exchange,提问作者xodiz
相关产品推荐
相关产品推荐

