Javascript onClick仅渲染一次(React)
我试图模仿复选框的行为,用户点击一行(来自“react flexbox grid”),复选框的图像被替换为选中或未选中 逻辑部分包含以下代码:Javascript onClick仅渲染一次(React),javascript,reactjs,Javascript,Reactjs,我试图模仿复选框的行为,用户点击一行(来自“react flexbox grid”),复选框的图像被替换为选中或未选中 逻辑部分包含以下代码: class Account extends React.Component { constructor(props) { super(props); this.state = { condition: true } this.handleSelect = this.handleSelect.bin
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}
/>
);
}
}
类帐户扩展React.Component{
建造师(道具){
超级(道具);
此.state={
条件:正确
}
this.handleSelect=this.handleSelect.bind(this);
}
handleSelect=(obj)=>{
这是我的国家({
条件:obj.condition
}
render(){
常数{
条件
}=本州;
返回(
);
}
}
视图部分如下所示:
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>
从'react flexbox grid'导入{Row,Col};
导出常量AccountView=(
{
条件
当选,
}
) => {
const renderCheckbox=(trueCond)=>{
返回trueCond?:
};
返回(
handleSelect({condition:!condition})}
>
{renderCheckbox(条件)}
这是一个复选框
我认为这是一个渲染问题,但我尝试使用componentDidUpdate重新渲染组件,但仍然不起作用。第一次单击行时,条件会更新并传递到AccountView,但第二次/第三次/第四次则不起作用。您不需要将
trueCond
传递到renderCheckbox
在状态更新之前,您正在传递它
将重新运行trueCond
替换为返回条件
您还需要在状态设置器中使用回调。在此代码中:
handleSelect=()=>{
这是我的国家({
条件:obj.condition
将其更改为:
handleSelect=()=>{
this.setState(prevState=>({
条件:!prevState.condition
}))
}
然后还:
onClick={()=>handleSelect()}
问题是,当我第二次单击该行时,我没有看到正在更新/传递给AccountView的props onSelect和condition。第一次单击它时,第二次/第三次/第四次什么都没有发生,但当我这样做时,我将无法编译警告“预期会有一个赋值或函数调用,但看到的却是一个表达式”错误出现在哪一行代码上?请原谅我的代码格式设置,我在手机上。这太不可思议了。错误出现在条件:!prevState.condition