1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- <script src="./babel.min.js"></script>
- <script src="./react.development.js"></script>
- <script src="./react-dom.development.js"></script>
- </head>
- <body>
- <div id="root"></div>
- <script type="text/babel">
- const root = ReactDOM.createRoot(document.getElementById("root"));
- // 判断:
- // if - else - else-if
- // switch case
- // 三元运算符:表达式 ? '真':'假'
- function App() {
- return(
- <div>
- <ToHome />
- </div>
- )
- }
- // 登录
- // 逻辑:用户 => 首页 ; 非用户 => 登录页
- // function ToHome(username) {
- // console.log(username,'哈哈哈哈')
- // return username.user ? <h1>欢迎光临</h1> : <h1>go out</h1>
- // }
- // 登录
- // 逻辑:用户 => 首页 ; 非用户 => 登录页
- // 手动设置是不是用户通过本地存储
- function ToHome() {
- let token = JSON.parse(localStorage.getItem("token"));
- function handleLogin() {
- localStorage.setItem("token", JSON.stringify({
- use:"喜羊羊",
- age: 7
- }))
- token = JSON.parse(localStorage.getItem("token"))
- console.log(token,'最新的')
- }
- return token ? (
- <h1>你好</h1>
- ) : (
- <div>
- <button onClick={handleLogin}>请登录</button>
- </div>
- )
- }
- class GoHome extends React.Component {
- constructor() {
- super();
- this.state = {
- token:JSON.parse(localStorage.getItem("token")),
- main:{
- name:"小明",
- age: 20
- }
- }
- this.handleLogin = this.handleLogin.bind(this);
- }
- handleLogin() {
- localStorage.setItem("token", JSON.stringify(this.state.main))
- this.setState({
- token: JSON.parse(localStorage.getItem("token"))
- })
- }
- render() {
- let {token} = this.state;
- return token ? (
- <h1>已登录</h1>
- ) : (
- <div>
- <h1>请注册</h1>
- <button onClick={this.handleLogin}>你好,请登录</button>
- </div>
- )
- }
- }
- root.render(<App/>)
- </script>
- </body>
- </html>
|