javascript - 如果单击复选框, react 如何将复选框从 true 更改为 false

标签 javascript reactjs checkbox ecmascript-6

正如标题所说,我想在单击时将复选框的值从 true 更改为 false 或从 false 更改为 true。我不知道如何改变它。我假设“setState”,但我不确定具体如何

toggleCheckboxChange(e) {

let isState = e.target.value;


if(isState != false) {
   isTrue = isState
}
if(isState == false) {
  isTrue = isState;
}
  //change state of checkbox
}
  render() {

weatherInfo = <WeatherInfo
      nameOfCity={nameOfCity}
      weatherDescription={weatherDescription}
      windSpeed={windSpeed}
      temperature={temperature}
      maxTemperature={maxTemperature}
      minTemperature={minTemperature}
      myPokemon={myPokemon}
      change={this.toggleCheckboxChange.bind(this)}
  />;


const WeatherInfo = (props) => (
<div>
    <ul>
        <li>{props.nameOfCity}</li>
        <li>{props.weatherDescription}</li>
        <li>{props.windSpeed} m/s </li>
        <li>{props.temperature} °C</li>
        <li>{props.maxTemperature}°C</li>
        <li>{props.minTemperature}°C</li>

        <input
            type="checkbox"
            value={false}
            onChange={(e)=>props.change(e)}
        />
    </ul>
</div>
);

最佳答案

您切换复选框的选中状态的方式不正确,因为如果您使用两个 if block ,则两个 block 都会被执行,因此即使第一个 block 执行,第二个 block 也会看到更新的内容结果并再次更改计算。

此外,您也不会重新调整更新的值或在状态中设置它。按照以下示例所示执行此操作。此外,在您的 WeatherInfo 组件中,您已将选中状态设置为 false,因此它将始终保持 false。您应该收到该 Prop 并将检查状态设置为此 Prop 。

还要确保将初始状态设置为 truefalse

toggleCheckboxChange(e) {

let isState = e.target.value;

if(isState == false) {
  isTrue = true;
}
else {
   isTrue=false;
}
  this.setState({checkedState: isTrue})
}
  render() {

weatherInfo = <WeatherInfo
      nameOfCity={nameOfCity}
      weatherDescription={weatherDescription}
      windSpeed={windSpeed}
      temperature={temperature}
      maxTemperature={maxTemperature}
      minTemperature={minTemperature}
      myPokemon={myPokemon}
      checkedState={this.props.checkedState}
      change={this.toggleCheckboxChange.bind(this)}
  />;


const WeatherInfo = (props) => (
<div>
    <ul>
        <li>{props.nameOfCity}</li>
        <li>{props.weatherDescription}</li>
        <li>{props.windSpeed} m/s </li>
        <li>{props.temperature} °C</li>
        <li>{props.maxTemperature}°C</li>
        <li>{props.minTemperature}°C</li>

        <input
            type="checkbox"
            value={props.checkedState}
            onChange={(e)=>props.change(e)}
        />
    </ul>
</div>
);

关于javascript - 如果单击复选框, react 如何将复选框从 true 更改为 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42557851/

相关文章:

javascript - mongodb - 在各个领域查找和替换部分字符串

php - 创建复选框以更改输出文本颜色

checkbox - 在 Laravel 中激活/停用多个客户端

java - 为复选框数组设置 OnClickListener

c# - JavaScript 日历问题

javascript - 使用复合组件的缺点

javascript - 基于子节点存在的过滤元素

javascript - 错误 : Must use import to load ES Module: D:\node_modules\react-markdown\index. 不支持 ES 模块的 js require()

reactjs - 如何在另一个函数中使用 useEffect() 中声明的变量?

reactjs - 从其他史诗中调用史诗