Welcome to OGeek Q&A 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 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...