Reactjs 复选框切换在react.js中工作不正常

Reactjs 复选框切换在react.js中工作不正常,reactjs,Reactjs,我的应用程序中有我的切换复选框。它不起作用了 我试过使用onChange函数,但它不起作用 复选框 <input id="switchCheckboxInputAssert" className="switch-checkbox-input" type="checkbox" checked={this.state.option.assert == 1 ? true : false} value={this.state.option.ass

我的应用程序中有我的切换复选框。它不起作用了

我试过使用onChange函数,但它不起作用


复选框

<input 
    id="switchCheckboxInputAssert" 
    className="switch-checkbox-input" 
    type="checkbox" 
    checked={this.state.option.assert == 1 ? true : false} 
    value={this.state.option.assert} 
    onChange={this.assertChange}
    disabled={!this.props.canBeSolution} 
/>

如何正确切换我的复选框?

您不需要使用
value
属性,只需使用
checked
属性,无需任何逻辑,因为您已经在react中处理复选框的登录
assertChange
函数

<input
  id="switchCheckboxInputAssert"
  className="switch-checkbox-input"
  type="checkbox"
  checked={this.state.option.assert}
  onChange={this.assertChange}
   />

工作演示

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component {
state = {
  option: {
    'something': 'new something',
    assert: true
  }
}
  assertChange = () => {
    this.setState({
      option: { ...this.state.option, assert: !this.state.option.assert }
    })
  }
  render() {
    console.log(this.state.option)
    return (
      <div className="App">
        <input
          id="switchCheckboxInputAssert"
          className="switch-checkbox-input"
          type="checkbox"
          checked={this.state.option.assert}
          onChange={this.assertChange}
           />
        <h2>Start editing to see some magic happen!</h2>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
从“React”导入React;
从“react dom”导入react dom;
导入“/styles.css”;
类应用程序扩展了React.Component{
状态={
选项:{
“某物”:“新的某物”,
断言:正确
}
}
资产变更=()=>{
这是我的国家({
选项:{…this.state.option,断言:!this.state.option.assert}
})
}
render(){
console.log(this.state.option)
返回(
开始编辑,看看神奇的发生!
);
}
}
const rootElement=document.getElementById(“根”);
render(,rootElement);
希望有帮助

我认为你把成分/元素弄混了。如果要允许复选框切换,则应将该值作为默认值而不是值传递,并将选中的值传递给回调函数

<input
  id="switchCheckboxInputAssert"
  className="switch-checkbox-input"
  type="checkbox"
  // pass state value as default checked value
  defaultChecked={this.state.option.assert}
  // pass checked value to callback
  onChange={evt => this.assertChange(evt.target.checked)}
  disabled={!this.props.canBeSolution}
/>
this.assertChange(evt.target.checked)}
disabled={!this.props.canBeSolution}
/>

您的代码是。只需检查您得到的
this.props.canBeSolution
true/false即可。
<input
  id="switchCheckboxInputAssert"
  className="switch-checkbox-input"
  type="checkbox"
  // pass state value as default checked value
  defaultChecked={this.state.option.assert}
  // pass checked value to callback
  onChange={evt => this.assertChange(evt.target.checked)}
  disabled={!this.props.canBeSolution}
/>