Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

关于react 使用 ref取实际的dom节点的问题

两个console的实际dom节点的值

这个不行

      let value 
       ...
      <input type="text" ref={( ref ) => {
        value = ref.value
      }}/>
      <button onClick={( e ) => {
        console.log(value)
      }}>确定
      </button>
      <button onClick={cancel}>取消</button>
      

这个可以

    let input
    ...
<form onSubmit={e => {
    e.preventDefault();
    if (!input.value.trim()) {
      return
    }
    console.log(input.value);
    input.value = ''
  }}>
    <input ref={node => {
      input = node
    }} />
    <button type="submit">
      确定
    </button>
    <button onClick={cancel}>取消</button>
</form>        

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

这句代码 我认为 value获取的是render那一时刻 input的值。
第二种,获取了input的引用,所以可以拿到input的值

ref={( ref ) => {
        value = ref.value
}}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...