React refs with components

前端 未结 2 1268
遇见更好的自我
遇见更好的自我 2020-12-13 10:39

I have React form that has a Component used to render a drop down because the options are coming from an API. However, I can\'t access the ref for the embedded component. I\

2条回答
  •  长情又很酷
    2020-12-13 11:28

    It is preferred to treat the ref as a callback attribute and no longer depend on the refs Object. If you do use the refs Object, avoid accessing refs of descendant components. You should treat refs as a private accessor and not part of a component's API. Treat only the methods exposed on a component instance as its public API.

    For this case, I suggest grabbing the form from the submit event and traversing its child form elements as needed. Add name attributes since that's how form elements are identified in standard form submissions, and then you shouldn't need refs at all:

    var ActivityForm = React.createClass({
      handleSubmit: function(e) {
        e.preventDefault();
        var form = e.target;
    
        // Use the standard [`HTMLFormElement.elements`][1] collection
        //
        // [1]: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements
        var content = form.elements['content'].value;
    
        // do more things with other named form elements
      },
      render: function() {
        return (
          

    New Activity