我正在尝试模仿checkbox的行为,用户点击某行(来自'react-flexbox-grid'),复选框的图像将被选中或未选中。
逻辑部分包含以下代码:
class Account extends React.Component {
constructor(props) {
super(props);
this.state = {
condition: true
}
this.handleSelect = this.handleSelect.bind(this);
}
handleSelect=(obj)=> {
this.setState({
condition: obj.condition
}
render() {
const {
condition,
} = this.state;
return (
<AccountView
condition={condition}
handleSelect={this.handleSelect}
/>
);
}
}视图部分如下:
import { Row, Col } from 'react-flexbox-grid';
export const AccountView = (
{
condition,
onSelect,
}
) => {
const renderCheckbox = (trueCond) => {
return trueCond ? <CheckedImg
src={boxCheckedIcon}
alt="checked check box"
/> : <UncheckedImg
src={boxUncheckedIcon}
alt="unchecked check box"
/>
};
return (
<Row
onClick={() => handleSelect({ condition: !condition})}
>
<Col>
{renderCheckbox(condition)}
</Col>
<Col >
This is a checkbox
</Col>
</Row>我认为这是渲染的问题,但我尝试使用componentDidUpdate重新渲染组件,但它仍然不起作用。第一次单击该行时,条件会更新并传递给AccountView,但第二次/第三次/第四次不会。
发布于 2020-08-25 06:17:12
您不需要将trueCond传递给renderCheckbox。在更新状态之前,您正在传递它。
用return condition替换retrun trueCond。
您还需要在状态设置器中使用回调。在此代码中:
handleSelect=()=> {
this.setState({
condition: obj.condition将其更改为:
handleSelect=()=> {
this.setState(prevState => ({
condition: !prevState.condition
}))
}然后也是:
onClick={() => handleSelect()}https://stackoverflow.com/questions/63569304
复制相似问题