P
P
Pavel Kizernis2019-11-20 01:03:08
JavaScript
Pavel Kizernis, 2019-11-20 01:03:08

ReactJS: How to properly describe Controlled Components?

Catching a bug

Warning: A component is changing an uncontrolled input of type radio to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://fb.me/react-controlled-components

The link above has a good example with event.preventDefault();,
but what if eventI need to pass more parameters in addition?
class Question extends React.Component {
  render() {
    return(
        <button className="btn btn2 exam-question__btn exam-question__btn-submit"
            onClick={this.handleClickAnswerCheck.bind(this, param1, param2)}>Ответить</button>
                  
    )
  }
  handleClickAnswerCheck = (param1, param2) => {
    let answer = document.getElementsByName('q'+param1);
    
    //answer - это input type="radio"
    //он и вызывает ошибку при клике на button
    
    //как запустить здесь
    //event.preventDefault(); или event.target...
    //?
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavel Didenko, 2019-11-20
@pashakiz

1. You are using class field syntax, so onClick={this.handleClickAnswerCheck.bind(this, param1, param2)} is not needed. Use like this onClick={(e) => handleClickAnswerCheck(e, param1, param2)}
2. You need to render your radiobutton via React and keep its state in state, not read it directly from DOM, that's why React swears

0
0xD34F, 2019-11-20
@0xD34F

besides eventI need to pass more parameters

Put them in data-attributes - they will be available through event.target.dataset.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question