【问题标题】:Refs are always null inside modal componentRefs 在模态组件中始终为空
【发布时间】:2019-10-22 02:36:31
【问题描述】:

所有在 reactstrap modal 组件中创建的 ref 在 compoenentDIDMount 中都是空的,无论它们是如何创建的

这与 react-dom 版本 16.8.6 有关。我尝试使用 react.createRef() 和回调直接分配 ref。

import { Modal, Form } from 'reactstrap'

class QuickBidModal extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          isOpen: false,
        };
        this.input1 = React.createRef();
    }

componentDidMount(){
  console.log(this.input1) //Always returns current as null
}

render(){
 <Modal>
  <Form>
  <div className="input" ref={this.input1} />
  </Form>

 </Modal>
}

我希望 this.input1 属于当前属性的输入类。但是,它只返回 null。如果我在 Modal 组件的外部创建 div 元素,则 ref 可以正常工作。

【问题讨论】:

  • 图书馆似乎没有考虑传递给其孩子的帐户 ref。它必须进行某种克隆以添加一些自定义道具,如果您可以将其他道具传递给它的孩子,请尝试检查文档。
  • 这里是源代码:github.com/reactstrap/reactstrap/blob/master/src/Form.js 你可以看到没有'this.props.children' 所以这意味着这个包没有考虑到孩子所以真正的问题是: 你到底能做到什么?如果我们查看源代码,他们总是使用标签道具并将其用作反应元素。所以也许你可以简单地将带有 ref 的标签道具传递给它。
  • @MaieonBrix 他们使用对象扩展语法将其余的道具(包括children)放入attributes 变量中,该变量将应用于别名Tag 下的组件。所以Tag 组件应该有children
  • 确实!谢谢@Rallen,那么也许我们可以使用 innerRef 道具?

标签: javascript reactjs reactstrap


【解决方案1】:

useRef 钩子在模态中不起作用,因为组件会挂载,但 jsx 不会渲染,直到你将 show prop 设置为 true。 useRef 本质上是异步的,这就是为什么在声明时它将 current 设置为 null 但在将其分配给任何元素 ref 之后得到它的值。但在模态的情况下,情况就不同了。这里的元素不是立即注册的,而是在 modal show prop 设置为 true 后注册的

为了解决这个问题,让 modal 的 show prop 始终为 true,并使整个组件动态显示/隐藏。例如。

const Child=()=>{
  const customRef=useRef(null);
  return(
     <Modal show={true}>
       <Modal.Body>
         <input ref={customRef} type="text"/>
       </Modal.Body>
    </Modal>
   );
}

const Parent=()=>{
   const [show,setShow]=useState=(false)
   return(
       <>
         <button onClick={()=>setShow(!show)}>Show/Hide Popup</button>
         {
           show?<Child/>:null
         }
       </>
   )
  }

【讨论】:

    猜你喜欢
    • 2018-11-25
    • 2018-10-02
    • 2015-09-12
    • 2015-05-21
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多