事件处理直接参考了慕课网上的教程,然后自己根据教程来编写实例,通过下面的实例可以很清晰地理解React的事件处理,其中需要注意的是索引refs!
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="https://cdn.bootcss.com/react/15.4.2/react.min.js"></script> <script src="https://cdn.bootcss.com/react/15.4.2/react-dom.min.js"></script> <script src="https://cdn.bootcss.com/babel-standalone/6.22.1/babel.min.js"></script> </head> <body> <div id="container"></div> <script type="text/jsx"> var TestClickComponent = React.createClass({ handleClick:function(event){ var tipE = React.findDOMNode(this.refs.tip); {/* 获取索引 */} if(tipE.style.display === ‘none‘){ tipE.style.display = ‘inline‘; }else{ tipE.style.display=‘none‘; } event.preventDefault(); event.stopPropagation(); }, render:function(){ return( <div> <button onclick={this.handleClick}>显示|隐藏</button><span ref="tip">测试点击</span> </div> ) } }); var TestInputComponent = React.createClass({ getInitialState:function(){ return { inputContent:‘‘ } }, changeHandler:function(event){ this.setState({ inputContent:event.target.value }) event.preventDefault(); event.stopPropagation(); }, render:function(){ return( <div> <input type="text" onChange={this.changeHandler} /><span>{this.state.inputContent}</span> </div> ) } }); ReactDOM.render( <div> <TestClickComponent></TestClickComponent> <TestInputComponent></TestInputComponent> </div>,document.getElementById("container") ) </script> </body> </html>
时间: 2024-10-16 19:01:32