【问题标题】:How to set React initial state based on radio buttons?如何根据单选按钮设置 React 初始状态?
【发布时间】:2021-07-06 13:28:23
【问题描述】:

所以我有一个兄弟组件,其状态受单选按钮影响

constructor (props){
    super(props);
    this.state = {
      selectedOption: "option1",
      bgColor: '',
    }
  }
  handleOptionChange = changeEvent => {
    this.setState({
      selectedOption: changeEvent.target.value,
      bgColor: changeEvent.target.name
    });
  };
  

  render() {
      return (
      <div>
      <CardBack fill={this.state.bgColor}/>
      <div>
        <label>
          <input
          type="radio"
          name="blue"
          value="option1"
          checked={this.state.selectedOption === "option1"}
          onChange={this.handleOptionChange}
          />
          Option 1
        </label>
        <label>
          <input
          type="radio"
          name="red"
          value="option2"
          checked={this.state.selectedOption === "option2"}
          onChange={this.handleOptionChange}
          />
          Option 2
        </label>
      </div>
      </div>
      )
    }
  }

我想让它的初始状态是通过选项 1 选择的任何颜色。在这种情况下为蓝色。我知道有办法做到这一点,但现在我不明白(我变黑了,这是 svg 填充的原始颜色)

【问题讨论】:

    标签: javascript reactjs components


    【解决方案1】:

    在实际渲染之前,您不能根据该组件中的输入名称设置该组件的状态。继续进行的最佳选择是将初始状态设置为“蓝色”/“红色”,具体取决于您首先要选择的内容(在您的情况下为“蓝色”)

    
        import ReactDOM from 'react-dom';
        import React, { Component } from 'react';
        
        const componentValue = document.querySelector("input[name=blue]");
        console.log(componentValue) // will evaluate to null
        
        class ComponentName extends Component {
          constructor (props){
            super(props);
            this.state = {
              selectedOption: "option1",
              bgColor: document.querySelector("input[name=blue]"),
            }
            console.log(this.state.bgColor)// will evaluate to null
          }
    
          handleOptionChange = changeEvent => {
            const componentValue = document.querySelector("input[name=blue]").name;
            console.log(componentValue); // will evaluate to "blue"
            this.setState({
              selectedOption: changeEvent.target.value,
              bgColor: changeEvent.target.name
            });
          };
    
          render({
            ...
          )}
        }
    

    【讨论】:

    • 好的,这就是我要做的,只是想知道是否有更简单的方法。 Tbh 我可能应该更改 UI,以便取消选择单选按钮
    【解决方案2】:

    我不确定你的问题是否正确,但你可以简单地将 bgColor 设置为 blue

    constructor (props){
        super(props);
        this.state = {
          selectedOption: "option1",
          bgColor: 'blue',
        } 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-02
      • 2021-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-17
      • 2019-09-02
      • 1970-01-01
      相关资源
      最近更新 更多