本篇文章讲述了react.js是如何实现动态字体颜色切换的,大家对于react.js实现动态字体颜色切换不太熟悉的同学可以和我们一起来看看本篇文章,废话少说,我们直接看看react.js是如何实现动态字体颜色切换的吧!
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title></title> <script src="https://static.runoob.com/assets/react/react-0.14.7/build/react.min.js"></script> <script src="https://static.runoob.com/assets/react/react-0.14.7/build/react-dom.min.js"></script> <script src="https://static.runoob.com/assets/react/browser.min.js"></script> </head> <body> <p id="example"></p> <script type="text/babel"> var LikeButton = React.createClass({ getInitialState: function() { return {liked: "yellow"}; }, handleClick: function(event) { this.setState({liked:"blue"}); }, render: function() { var text = this.state.liked; var style = { color:text }{/*css样式既可以写在组件内也可以写在组件外*/} return ( <p onClick={this.handleClick} style={style}>{/*这里不能直接用如style={color:"yellow"}这种属性赋予方式*/} 点我,点我,点我我就变身。 </p> ); } }); React.render( <LikeButton />, document.getElementById('example') ); </script> </body> </html>
这种方式只能实现点击一次切换样式。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title></title> <script src="https://static.runoob.com/assets/react/react-0.14.7/build/react.min.js"></script> <script src="https://static.runoob.com/assets/react/react-0.14.7/build/react-dom.min.js"></script> <script src="https://static.runoob.com/assets/react/browser.min.js"></script> </head> <body> <p id="example"></p> <script type="text/babel"> var LikeButton = React.createClass({ getInitialState: function() { return {liked: false}; }, handleClick: function(event) { this.setState({liked:!this.state.liked}); }, render: function() { var text = this.state.liked?"yellow":"blue"; var style = { color:text } return ( <p onClick={this.handleClick} style={style}> 你我。点我切换状态。 </p> ); } }); React.render( <LikeButton />, document.getElementById('example') ); </script> </body> </html>
两者之间没什么多大的区别,主要是第二种运用了三元运算符,实现了点击循环切换的功能。
相关推荐:
以上是react.js实现动态字体颜色切换讲述的详细内容。更多信息请关注PHP中文网其他相关文章!