我想在3个酒吧中选择某些酒吧在react.js中怎么做?
这是我的代码:
var Progressbar = React.createClass({ getInitialState: function() { return {completed:this.props.completed}; },addPrecent: function(value){ this.props.completed+=value; this.setState({completed:this.props.completed}); },render: function() { var completed = this.props.completed; if (completed < 0) {completed = 0}; return (...); }
我想使用这个反应组件:
var App = React.createClass({ getInitialState: function() { return {baction: 'Progress1'}; },handleChange: function(e){ var value = e.target.value; console.log(value); this.setState({baction:value}); },handleClick10:function(e){ console.log('You clicked: ',this.state.baction ); document.getElementById(this.state.baction).addPrecent(10); },render: function() { return ( <div class="center">Progress Bars Demo <Progressbar completed={25} id="Progress1"/> <h2 class="center"></h2> <Progressbar completed={50} id="Progress2"/> <h2 class="center"></h2> <Progressbar completed={75} id="Progress3"/> <h2 class="center"></h2> <span> <select name='selectbar' id='selectbar' value={this.state.baction} onChange={this.handleChange}> <option value="Progress1">#Progress1</option> <option value="Progress2">#Progress2</option> <option value="Progress3">#Progress3</option> </select> <input type="button" onClick={this.handleClick10} value="+10"/> <button>+25</button> <button>-10</button> <button>-25</button> </span> </div> ) } });
我想执行handleClick10函数,并对我所选的进度条进行操作.
但我得到的结果是:
You clicked: Progress1 TypeError: document.getElementById(...) is null
如何在react.js中选择某个元素?
你可以通过指定参考文献来做到这一点
原文链接:https://www.f2er.com/react/300723.html<Progressbar completed={25} id="Progress1" ref="Progress1"/> <h2 class="center"></h2> <Progressbar completed={50} id="Progress2" ref="Progress2"/> <h2 class="center"></h2> <Progressbar completed={75} id="Progress3" ref="Progress3"/>
为了得到元素只是做
var object = this.refs.Progress1;
等等…
编辑
然而,Facebook建议反对它,因为字符串引用有一些问题,被认为是遗产,并且可能会在以后的版本中删除.
推荐的方法是使用回调模式
我希望它有帮助
<Progressbar completed={25} id="Progress1" ref={(input) => {this.Progress[0] = input }}/> <h2 class="center"></h2> <Progressbar completed={50} id="Progress2" ref={(input) => {this.Progress[1] = input }}/> <h2 class="center"></h2> <Progressbar completed={75} id="Progress3" ref={(input) => {this.Progress[2] = input }}/>