如何在 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 (...); }
我想使用这个 React 组件:
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 中选择特定元素?
要获取元素,react您需要使用ref并在函数内部使用该ReactDOM.findDOMNode方法。
react
ref
ReactDOM.findDOMNode
但我更喜欢做的是在事件内部调用 ref
<input type="text" ref={ref => this.myTextInput = ref} />
这是一些很好的链接,可以帮助您弄清楚。