[英]onClick renders only once (React)
我試圖模仿復選框的行為,用戶點擊一行(來自'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,但第二/第三個第四,它沒有。
您不需要將trueCond
傳遞給renderCheckbox
。 您正在狀態更新之前傳遞它。
用return condition
替換retrun trueCond
。
您還需要在狀態設置器中使用回調。 在這段代碼中:
handleSelect=()=> {
this.setState({
condition: obj.condition
將其更改為:
handleSelect=()=> {
this.setState(prevState => ({
condition: !prevState.condition
}))
}
然后還有:
onClick={() => handleSelect()}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.