How can I attach to a stateless component's ref in React?

后端 未结 5 2233
悲哀的现实
悲哀的现实 2020-12-08 03:48

I am looking to create a stateless component who\'s input element can be validated by the parent component.

In my example below, I am running into a pro

相关标签:
5条回答
  • 2020-12-08 04:08

    EDIT: You now can with React Hooks. See the answer by Ante Gulin.

    You can't access React like methods (like componentDidMount, componentWillReceiveProps, etc) on stateless components, including refs. Checkout this discussion on GH for the full convo.

    The idea of stateless is that there isn't an instance created for it (state). As such, you can't attach a ref, since there's no state to attach the ref to.

    Your best bet would be to pass in a callback for when the component changes and then assign that text to the parent's state.

    Or, you can forego the stateless component altogether and use an normal class component.

    From the docs...

    You may not use the ref attribute on functional components because they don't have instances. You can, however, use the ref attribute inside the render function of a functional component.

    function CustomTextInput(props) {
      // textInput must be declared here so the ref callback can refer to it
      let textInput = null;
    
      function handleClick() {
        textInput.focus();
      }
    
      return (
        <div>
          <input
            type="text"
            ref={(input) => { textInput = input; }} />
          <input
            type="button"
            value="Focus the text input"
            onClick={handleClick}
          />
        </div>
      );  
    }
    
    0 讨论(0)
  • 2020-12-08 04:15

    The value of your TextInput is nothing more than a state of your component. So instead of fetching the current value with a reference (bad idea in general, as far as I know) you could fetch the current state.

    In a reduced version (without typing):

    class Form extends React.Component {
      constructor() {
        this.state = { _emailAddress: '' };
    
        this.updateEmailAddress = this.updateEmailAddress.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
      }
    
      updateEmailAddress(e) {
        this.setState({ _emailAddress: e.target.value });
      }
    
      handleSubmit() {
        console.log(this.state._emailAddress);
      }
    
      render() {
        return (
          <form onSubmit={this.handleSubmit}>
            <input
              value={this.state._emailAddress}
              onChange={this.updateEmailAddress}
            />
          </form>
        );
      }
    }
    
    0 讨论(0)
  • 2020-12-08 04:16

    This is late but I found this solution much better. Pay attention to how it uses useRef & how properties are available under current property.

    function CustomTextInput(props) {
      // textInput must be declared here so the ref can refer to it
      const textInput = useRef(null);
    
      function handleClick() {
        textInput.current.focus();
      }
    
      return (
        <div>
          <input
            type="text"
            ref={textInput} />
          <input
            type="button"
            value="Focus the text input"
            onClick={handleClick}
          />
        </div>
      );
    }
    

    For more reference check react docs

    0 讨论(0)
  • 2020-12-08 04:29

    You can useuseRef hook which is available since v16.7.0-alpha.

    EDIT: You're encouraged to use Hooks in production as of 16.8.0 release!

    Hooks enable you to maintain state and handle side effects in functional components.

    function TextInputWithFocusButton() {
      const inputEl = useRef(null);
      const onButtonClick = () => {
        // `current` points to the mounted text input element
        inputEl.current.focus();
      };
      return (
        <>
          <input ref={inputEl} type="text" />
          <button onClick={onButtonClick}>Focus the input</button>
        </>
      );
    }
    

    Read more in Hooks API documentation

    0 讨论(0)
  • 2020-12-08 04:31

    You can also get refs into functional components with a little plumbing

    import React, { useEffect, useRef } from 'react';
    
    // Main functional, complex component
    const Canvas = (props) => {
      const canvasRef = useRef(null);
    
        // Canvas State
      const [canvasState, setCanvasState] = useState({
          stage: null,
          layer: null,
          context: null,
          canvas: null,
          image: null
      });
    
      useEffect(() => {
        canvasRef.current = canvasState;
        props.getRef(canvasRef);
      }, [canvasState]);
    
    
      // Initialize canvas
      useEffect(() => {
        setupCanvas();
      }, []);
    
      // ... I'm using this for a Konva canvas with external controls ...
    
      return (<div>...</div>);
    }
    
    // Toolbar which can do things to the canvas
    const Toolbar = (props) => {
      console.log("Toolbar", props.canvasRef)
    
      // ...
    }
    
    // Parent which collects the ref from Canvas and passes to Toolbar
    const CanvasView = (props) => {
      const canvasRef = useRef(null);
    
      return (
        <Toolbar canvasRef={canvasRef} />
        <Canvas getRef={ ref => canvasRef.current = ref.current } />
    }
    
    0 讨论(0)
提交回复
热议问题