React在html中的应用

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app"></div>
  <script src="./node_modules/react/umd/react.development.js"></script>//npm i react
  <script src="./node_modules/react-dom/umd/react-dom.development.js"></script>// npm i react
  <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
  <script src="./node_modules/prop-types/prop-types.min.js"></script>// npm install i prop-types
  <script type="text/babel">
    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          todos: ['AAA', 'BBB', 'CCC']
        };
        this.addTodo=this.addTodo.bind(this)
      }
      addTodo(todo){
        const {todos}=this.state
        todos.unshift(todo)
        this.setState({todos})
      }
      render() {
        const { todos } = this.state;
        return (
          <div>
            Simple TODO list
            <Add count={todos.length}   addTodo={this.addTodo}/>
            <List todos={todos}/>
          </div>
        )
      }
    }
    class Add extends React.Component {
      constructor(props) {
        super(props);
        this.add = this.add.bind(this)
      }
      add() {
        const todo=this.todoInput.value.trim();
        if(!todo) return
        this.props.addTodo(todo)
        this.todoInput.value=''
      }
      render() {
        return (
          <div>
            <input type="text" ref={input => this.todoInput = input} />
            <button onClick={this.add}>add #{this.props.count + 1}</button>
          </div>
        )
      }
    }
    Add.propTypes = {
      count: PropTypes.number.isRequired,
      addTodo:PropTypes.func.isRequired
    }
    class List extends React.Component {
      render() {
        const { todos } = this.props
        return (
          <ul>
            {todos.map((todo, key) => (<li key={key}>{todo}</li>))}
          </ul>
        )
      }
    }
    List.propTypes = {
      todos: PropTypes.array.isRequired
    }
    ReactDOM.render(<App />, document.getElementById('app'));
  </script>
</body>

</html>

  

原文地址:https://www.cnblogs.com/junechen/p/14388204.html