Home > Article > Web Front-end > React.js implements dynamic font color switching description
This article describes how react.js implements dynamic font color switching. Students who are not familiar with react.js implementing dynamic font color switching can take a look at this article with us. Stop talking nonsense. Let’s take a look directly at how react.js implements dynamic font color switching!
<!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>
This method can only switch styles with one click.
<!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>
There is not much difference between the two. The main reason is that the second method uses the ternary operation operator to achieve click Loop switching function.
Related recommendations:
react.js gives the identifier ref and gets the content
Use a very simple example to understand the idea of react.js high-order components
The above is the detailed content of React.js implements dynamic font color switching description. For more information, please follow other related articles on the PHP Chinese website!