【问题标题】:React Js: Accessing ref in another componentReact Js:在另一个组件中访问 ref
【发布时间】:2019-12-04 06:52:43
【问题描述】:

我在一个组件中有一个带有 ref 的文本框(modalBox.js)我如何在按钮单击时访问另一个组件上的文本框的值,例如(index.js)

【问题讨论】:

    标签: reactjs react-component react-ref


    【解决方案1】:

    在 react 中检查 refForwarding。 https://reactjs.org/docs/forwarding-refs.html

    【讨论】:

      【解决方案2】:

      假设您在Component1 中有一个input 字段 -

      const Component1 = props => {
        let textInput = useRef(null);
      
        const handleOnChange = event => {
          props.onChange(textInput)
        }
      
        return ( 
          <input onChange={handleOnChane} ref={textInput} /> 
        )
      }
      

      现在来自另一个组件,您要在其中捕获引用 -

      <Component1 onChange = {ref => console.log(ref) } />
      

      这里我只是在控制台中打印 ref 对象。但你可以为所欲为。

      【讨论】:

        【解决方案3】:
        const MyComponent = React.forwardRef((props, ref) => (
          <button ref={ref}>
            Click me
          </button>
        ));
        
        
        const ref = React.createRef();
        <MyComponent ref={ref}>Click me!</MyComponent>;
        

        【讨论】:

          猜你喜欢
          • 2018-11-18
          • 2022-11-17
          • 2020-12-06
          • 2018-01-26
          • 1970-01-01
          • 1970-01-01
          • 2019-05-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多