加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

React学习入门实例

发布时间:2020-12-15 04:41:53 所属栏目:百科 来源:网络整理
导读:上节中接触的react hello world例子中引用了三个框架脚本文件,react.js 、react-dom.js 和 Browser.js ,它们必须首先加载。其中,react.js 是 React 的核心库,react-dom.js 是提供与 DOM 相关的功能,Browser.js 的作用是将 JSX 语法转为 JavaScript 语法

上节中接触的react hello world例子中引用了三个框架脚本文件,react.js 、react-dom.js 和 Browser.js ,它们必须首先加载。其中,react.js 是 React 的核心库,react-dom.js 是提供与 DOM 相关的功能,Browser.js 的作用是将 JSX 语法转为 JavaScript 语法,这一步很消耗时间,实际上线的时候,应该将它放到服务器完成。

注意:browser.js这个和那个开源的bowser.js不一样,那个是用来检测浏览器的小脚本,和BOWSER.JS也不一样,那个是一个JS 3D网页游戏开发的库,和bower也不一样,那个是一个包管理工具,这些名字呀,老纳也是醉了。

这是一个timer计时器的官方例子,直接把组件加到body里,整个源码:

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style> * { padding:0; margin:0; } html{ font:14px normal Arial,sans-serif; color:#626771; } body{ padding:60px; text-align: center; } </style>
    <script src="../react.min.js"></script>
    <script src="../react-dom.min.js"></script>
    <script src="../browser.min.js"></script>
</head>
<body>
    <script type="text/babel"> var TimerExample = React.createClass({ getInitialState: function(){ return { elapsed: 0 }; },componentDidMount: function(){ this.timer = setInterval(this.tick,50); },componentWillUnmount: function(){ clearInterval(this.timer); },tick: function(){ this.setState({elapsed: new Date() - this.props.start}); },render: function() { var elapsed = Math.round(this.state.elapsed / 100); var seconds = (elapsed / 10).toFixed(1); return <p>This example was started <b>{seconds} seconds</b> ago.</p>; } }); React.render( <TimerExample start={Date.now()} />,document.body ); </script>
</body>
</html>

定义了一个组件TimerExample ,里面componentDidMount和componentWillUnmount是五个事件中的其中两个,分别表示组件加载完成和组件将被卸载,这里用来初始化计时器和清除计时器。getInitialState设置了一个变量elapsed 初始值为0,计时器每隔50ms执行一次tick方法,设置elapsed 为当前时间减去初始时间,初始时间被定义成了组件的属性start,在组件里获取属性的方式是通过this.props,render返回了格式化的HTML,秒数被格式化保留一位小数。

这个例子很容易理解,里面组件的定义,数据的处理,组件如何被使用都很清楚。

再看一个导航菜单的例子:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style> * { padding:0; margin:0; } html{ font:14px normal Arial,sans-serif; color:#626771; background-color:#fff; } body{ padding:60px; text-align: center; } ul{ list-style:none; display: inline-block; } ul li{ display: inline-block; padding: 10px 20px; cursor:pointer; background-color:#eee; color:#7B8585; transition:0.3s; } ul li:hover{ background-color:#beecea; } ul li.focused{ color:#fff; background-color:#41c7c2; } p{ padding-top:15px; font-size:12px; } </style>
    <script src="../react.min.js"></script>
    <script src="../react-dom.min.js"></script>
    <script src="../browser.min.js"></script>
</head>
<body>
    <script type="text/babel"> var MenuExample = React.createClass({ getInitialState: function(){ return { focused: 0 }; },clicked: function(index){ this.setState({focused: index}); },render: function() { var self = this; return ( <div> <ul>{ this.props.items.map(function(m,index){ var style = ''; if(self.state.focused == index){ style = 'focused'; } return <li className={style} onClick={self.clicked.bind(self, index)}>{m}</li>; }) } </ul> <p>Selected: {this.props.items[this.state.focused]}</p> </div> ); } }); React.render( <MenuExample items={ ['Home','Services','About','Contact us'] } />,document.body ); </script>
</body>
</html>

这个导航菜单使用一个变量focused来标记选中的是哪一个,虽然很原始,但扩展一下就可以在项目里用了,哈哈。

搜索智 能提示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style> * { padding:0; margin:0; } html{ font:14px normal Arial,sans-serif; color:#626771; background-color:#fff; } body{ padding:60px; text-align: center; } input[type=text]{ text-align: center; font: inherit; border: 6px solid #a3d8d6; padding: 13px 12px; font-size: 15px; box-shadow: 0 1px 1px #DDD; width: 384px; outline: none; display: block; color: #7B8585; margin: 0 auto 20px; } ul{ list-style: none; display: inline-block; width: 420px; text-align: left; } ul li{ display: block; padding: 15px 20px; background-color: #F8F8F8; color: #7B8585; margin-bottom: 3px; position: relative; transition: 0.3s; } ul li a{ position: absolute; left: 160px; font-size: 12px; line-height: 16px; color: #969d9d; } ul li:hover{ background-color:#d8f2f1; } </style>
    <script src="../react.min.js"></script>
    <script src="../react-dom.min.js"></script>
    <script src="../browser.min.js"></script>
</head>
<body>
    <script type="text/babel"> var SearchExample = React.createClass({ getInitialState: function(){ return { searchString: '' }; },handleChange: function(e){ this.setState({searchString:e.target.value}); },render: function() { var libraries = this.props.items,searchString = this.state.searchString.trim().toLowerCase(); if(searchString.length > 0){ libraries = libraries.filter(function(l){ return l.name.toLowerCase().match( searchString ); }); } return <div> <input type="text" value={this.state.searchString} onChange={this.handleChange} placeholder="Type here" /> <ul> { libraries.map(function(l){ return <li>{l.name} <a href={l.url}>{l.url}</a></li> }) } </ul> </div>; } }); var libraries = [ { name: 'Backbone.js',url: 'http://documentcloud.github.io/backbone/'},{ name: 'AngularJS',url: 'https://angularjs.org/'},{ name: 'jQuery',url: 'http://jquery.com/'},{ name: 'Prototype',url: 'http://www.prototypejs.org/'},{ name: 'React',url: 'http://facebook.github.io/react/'},{ name: 'Ember',url: 'http://emberjs.com/'},{ name: 'Knockout.js',url: 'http://knockoutjs.com/'},{ name: 'Dojo',url: 'http://dojotoolkit.org/'},{ name: 'Mootools',url: 'http://mootools.net/'},{ name: 'Underscore',url: 'http://documentcloud.github.io/underscore/'},{ name: 'Lodash',url: 'http://lodash.com/'},{ name: 'Moment',url: 'http://momentjs.com/'},{ name: 'Express',url: 'http://expressjs.com/'},{ name: 'Koa',url: 'http://koajs.com/'} ]; React.render( <SearchExample items={ libraries } />,document.body ); </script>
</body>
</html>

就一个handleChange和filter就简单地实现了强大的过滤功能,react真的挺好用的。

表格计算

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style> * { padding:0; margin:0; } html{ font:14px normal Arial,sans-serif; color:#626771; background-color:#fff; } body{ padding:60px; text-align: center; } h1{ font-size:18px; margin-bottom:20px; } #services{ list-style: none; display: inline-block; width: 340px; text-align: left; } #services p{ display: block; padding: 15px 20px; background-color: #F8F8F8; color: #7B8585; margin-bottom: 3px; position: relative; cursor: pointer; transition: 0.3s; } #services p b{ position: absolute; right: 28px; line-height: 16px; width: 100px; color: #808787; text-align: right; } #services p:hover{ background-color:#d8f2f1; } #services p.active{ color:#fff; background-color:#41c7c2; } #services p.active b{ color: #fff; } #total{ background: none !important; cursor: default !important; padding-top: 10px !important; } </style>
    <script src="../react.min.js"></script>
    <script src="../react-dom.min.js"></script>
    <script src="../browser.min.js"></script>
</head>
<body>
    <script type="text/babel"> var ServiceChooser = React.createClass({ getInitialState: function(){ return { total: 0 }; },addTotal: function( price ){ this.setState( { total: this.state.total + price } ); },render: function() { var self = this; var services = this.props.items.map(function(s){ return <Service name={s.name} price={s.price} active={s.active} addTotal={self.addTotal} />; }); return <div> <h1>Our services</h1> <div id="services"> {services} <p id="total">Total <b>${this.state.total.toFixed(2)}</b></p> </div> </div>; } }); var Service = React.createClass({ getInitialState: function(){ return { active: false }; },clickHandler: function (){ var active = !this.state.active; this.setState({ active: active }); this.props.addTotal( active ? this.props.price : -this.props.price ); },render: function(){ return <p className={ this.state.active ? 'active' : '' } onClick={this.clickHandler}> {this.props.name} <b>${this.props.price.toFixed(2)}</b> </p>; } }); var services = [ { name: 'Web Development',price: 300 },{ name: 'Design',price: 400 },{ name: 'Integration',price: 250 },{ name: 'Training',price: 220 } ]; React.render( <ServiceChooser items={ services } />,document.body ); </script>
</body>
</html>

这个例子演示了两个组件怎么配合使用,ServiceChooser 使用了Service组件,一个Service 相当于一行,而ServiceChooser 是Service的组合,根据click事件和state.active来控制总量的计算。

以上示例均来自官方,代码整合到一个html文件中,直接运行就可见效果。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读