React - passing refs as a prop

后端 未结 2 633
夕颜
夕颜 2021-02-06 08:07

I am trying to manage a checkbox with react. The following code works well enough, but I want to refactor out the code in the render method so that it uses a Component. I want

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-06 08:38

    Pass a callback ref into the Component, like that:

     (this.checkbox = ref)} />
    

    Oh, and by the way, please always use callback refs. Read more here.

    One more idea to consider for you: Move the checked value of the checkbox fully into the state of the AreRefsAwesomeCheckbox component and use a fully controlled component. That's always better than a ref with bigger predictability and less surprises.

    Full code:

    const Checkbox = ({myRef, changeInput, checkboxText}) => {
      return (
        
      )
    }
    
    export default class AreRefsAwesomeCheckbox extends Component {
      constructor(props) {
        super(props)
        this.handleInputChange = this.handleInputChange.bind(this)
      }
    
      handleInputChange() {
        let data = {
          isFeatured: this.refs.check_me.checked,
        }
    
        postJSON('/some/url', data)
      }
    
      componentDidMount() {
        const data = getJSON('/some/url')
        data.then(object => {
          // this.checkbox is the reference to the checkbox element you need
          this.checkbox.checked = object.will_i_have_a_nice_checkbox
        })
      }
    
      render() {
        return (
          
    ) } }

提交回复
热议问题