反应js,得到兄弟姐妹或父母价值 [英] react js , get siblings or parent value

查看:139
本文介绍了反应js,得到兄弟姐妹或父母价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有新的反应,我很好奇如何正确地做到这一点。
假设我有这个表单,点击按钮,我想得到文本框值,

I'm new to react, I'm curious how to do this properly. suppose I have this form, by clicking button, I want to get textbox value,

var form = React.createClass({
   submit : function(e){
      //how to get textbox value?
   },
   render : function(){
   return (
      <form>
         <input type="text" id="textbox" value="hey, get me"/>
         <button onClick={this.submit}>Get it</button>
      </form>
      );
   }
});

任何答案都将不胜感激!谢谢!

Any answer will be appreciated! thank you!

推荐答案

实现此目的的一种方法是使用refs。

One way to accomplish this is using refs.


构建组件后,您可能会发现自己想要达到
out并调用从render返回的组件实例上的方法()。 链接到参考文档

Refs基本上是你想要访问的html元素/反应实例。在这种情况下,我们想要获取Input html元素。我们通过this.inputValue获取输入元素。然后按照通常的js规则读取它的值。

Refs are basically the html elements / react instances you want to access. In this case, we want to get Input html element. We get input element by this.inputValue. Then read its value by usual js rule.

 var form = React.createClass({
       submit : function(e){
          e.preventDefault();
          console.log(this.inputValue.value);
       },
       render : function(){
       return (
          <form onSubmit={this.submit}>
             <input type="text" id="textbox" defaultValue="hey, get me"
               ref={ function(node){ this.inputValue = node }.bind(this) }
             />
             <button onClick={this.submit}>Get it</button>
          </form>
          );
       }
    });

这里是

here is a jsfiddle for your example, you can check the console for the input value.

另一种完成同样事情的方法是制作你输入一个受控元素。这意味着您将输入的值属性分配给this.state.inputValue,并将onChange事件处理程序作为onChange = {yourInputHandlerFunction}传递。

Another way to accomplish the same thing is to make your input a controlled element. That means you assign input's value attribute to this.state.inputValue and you pass a onChange event handler as onChange={yourInputHandlerFunction}.

请参阅解释此方法的答案完成同样的事情。

See the answer which explains this way of accomplishing the same thing.

这篇关于反应js,得到兄弟姐妹或父母价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆