ReactJS: How to use boolean values ​​in switches?

What is the correct way to use boolean data in switches. Values ​​will be converted from boolean strings to strings if they are used directly.

JSON data for preloaded input fields:

var question = [
  {value: true, name: "Yes"},
  {value: false, name: "Not this time"}
]

Switch Fields:

<input type="radio" 
       name="question" 
       onChange={this.state.onRadioChange} 
       value={this.state.question[0].value} /> {this.state.question[0].name}
<input type="radio" 
       name="question" 
       onChange={this.state.onRadioChange} 
       value={this.state.question[1].value} /> {this.state.question[1].name}

Binding for onRadioChange:

onRadioChange: function(e) {
    console.log(e.target.value);
}

The console log shows that the selected values ​​are converted from boolean strings to strings.

onRadioChange "true"/"false" booleans e.target.value, . , "e.target.checked" , , booleans ( ).

, REST.

- ReactJS? , .

+6
4

boolean .

var function = str2bool(value) {
   if (value && typeof value === 'string') {
     if (value.toLowerCase() === "true") return true;
     if (value.toLowerCase() === "false") return false;
   }
   return value;
}

:

onRadioChange: function(e) {
    console.log(str2bool(e.target.value));
    // Here we can send the data to further processing (Action/Store/Rest)
}

, Rest Stores .

+5

. .

+5

, React, :

var RadioButtons = React.createClass({
  getInitialState: function () {
    // Assuming there is always one option set to true.
    return {
      question: this.props.options.filter(function (option) {
        return option.value;
      })[0].name
    };
  },
  onRadioChange: function (e) {
    this.setState({
      question: e.target.value
    });
  },
  render: function () {
    var options = this.props.options.map(function (option, key) {
      return (
        <li key={key}>
          <input type="radio" 
             name="question" 
             onChange={this.onRadioChange} 
             checked={this.state.question === option.name}
             value={option.name} /> {option.name}
        </li>
      );
    }, this);
    return (
      <ul style={{listStyle: 'none'}}>
        {options}
      </ul>
    );
  }
});

question :

<RadioButtons options={question} />

fiddle.

+2

/ - , target.checked. , , - .

target.checked ( ), . , target.checked handleChange() true, , , target.checked true (, false).

function handleChange(e) {
  const value = e.target.value;
  setState({answer: value});
}

<input
  type="radio"
  name="answer"
  onChange={handleChange}
  value="yes"
  checked={answer === "yes"}
/> Yes

<input
  type="radio"
  name="answer"
  onChange={handleChange}
  value="no"
  checked={answer === "no"}
/> Not this time

: https://codesandbox.io/s/stack-overflow-34547733-nc04l

0

Source: https://habr.com/ru/post/1622349/


All Articles