admin 管理员组文章数量: 1086019
So my code looks like so:
stockconfirmbuy: function(){
var totalbuyval = this.refs.stockpriceref.innerHTML * this.refs.stockdnum.value;
return (<div>
<input type="number" value="1" ref="stockdnum" />
<p>Your Total:</p>
<p>${totalbuyval}</p>
</div>);
},
My problem here is that I get a Cannot read property 'value' of undefined
error. This refers to my input type="number"
.
However, I have been trying to give my input a default value so that this does not occur. I gave it a default value=1
, but this does not seem to satisfy the ref.
So I am wondering what I need to do to set a default ref value. Or should I be using state?
So my code looks like so:
stockconfirmbuy: function(){
var totalbuyval = this.refs.stockpriceref.innerHTML * this.refs.stockdnum.value;
return (<div>
<input type="number" value="1" ref="stockdnum" />
<p>Your Total:</p>
<p>${totalbuyval}</p>
</div>);
},
My problem here is that I get a Cannot read property 'value' of undefined
error. This refers to my input type="number"
.
However, I have been trying to give my input a default value so that this does not occur. I gave it a default value=1
, but this does not seem to satisfy the ref.
So I am wondering what I need to do to set a default ref value. Or should I be using state?
Share Improve this question asked Aug 30, 2016 at 23:21 Jason ChenJason Chen 2,5776 gold badges27 silver badges47 bronze badges4 Answers
Reset to default 3You should absolutely be using state here, set default state value with getInitialState()
for both stockdnum
and stockpriceref
You then can render the value from state, e.g. <input type="number" value={this.state.stockdnum}/>
. Note that this will cause the input to be read-only unless you set up an onChange
to update state. Read more about this here
I doubt you need refs at all for this, and in fact you should avoid them if possible. They're more for providing raw DOM refs to non-React APIs (e.g. jQuery or TweenLite or something)
Also, string refs as you are using them there will likely be removed in the future anyway
I have been trying to give my input a default value so that this does not occur
you can do something like this :
var defaultRef = typeof this.refs.stockdnum.value !== "undefined" ? this.refs.stockdnum.value : defaultValue;
var totalbuyval = this.refs.stockpriceref.innerHTML * defaultRef;
you can you defaultValue attribute
<input type="text" ref={nameRef} name="name" placeholder="Enter name..." defaultValue={...yourvalue} />
I solved it by assigning the initial value in ponentDidMount. I was receiving initial value through props. Take a look.
本文标签: javascriptSet a default ref value on ReactStack Overflow
版权声明:本文标题:javascript - Set a default ref value on React? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744025074a2520487.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论