onClick仅渲染一次(反应)

时间:2020-08-24 22:06:26

标签: javascript reactjs

我正在尝试模仿复选框的行为,即用户单击行(来自“ 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,但第二/三四则不会。

1 个答案:

答案 0 :(得分:1)

您无需将trueCond传递给renderCheckbox。您是在状态更新前通过它的。

retrun trueCond替换为return condition

您还需要在状态设置器中使用回调。在此代码中:

handleSelect=()=> {
      this.setState({
        condition: obj.condition

将其更改为:

handleSelect=()=> {
      this.setState(prevState => ({
        condition: !prevState.condition
  }))
}

然后:

onClick={() => handleSelect()}