<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>05_components_composing</title> </head> <body> <div id="example"></div> <script type="text/javascript" src="../js/react.development.js"></script> <script type="text/javascript" src="../js/react-dom.development.js"></script> <script type="text/javascript" src="../js/prop-types.js"></script> <script type="text/javascript" src="../js/babel.min.js"></script> <script type="text/babel"> /* 1)拆分组件: 拆分界面,抽取组件 2)实现静态组件: 使用组件实现静态页面效果 3)实现动态组件 ① 动态显示初始化数据 ② 交互功能(从绑定事件监听开始) */ /* * 问题:数据保存在哪个组件中? * 看数据是某个组件需要(给他),还是某些组件需要(给共同的父组件) * 问题2:需要在子组件中改变父组件的状态 * 状态在哪个组件,更新状态的行为就应该定义在哪个组件 * 解决:父组件定义函数,传递给子组件,子组件调用 * */ // 应用组件 class App extends React.Component { constructor(props) { super(props) // 初始化状态 this.state = { todos: [‘吃饭‘, ‘睡觉‘, ‘打豆豆‘] } this.add = this.add.bind(this) } add(todo) { const {todos} = this.state todos.unshift(todo) //更新状态 this.setState({todos}) } render() { const {todos} = this.state return ( <div> <TodoAdd add={this.add} count={todos.length}/> <TodoList todos={todos}/> </div> ) } } // 添加todo组件 class TodoAdd extends React.Component { constructor(props) { super(props) this.addTodo = this.addTodo.bind(this) } addTodo() { // 读取输入数据 const text = this.input.value.trim() // 查检 if (!text) { return } // 保存到todos this.props.add(text) // 清除输入 this.input.value = ‘‘ } render() { return ( <div> <h2>Simple TODO List</h2> <input type="text" ref={input => this.input = input}/> <button onClick={this.addTodo}>Add #{this.props.count}</button> </div> ) } } TodoAdd.propTypes = { add: PropTypes.func.isRequired, count: PropTypes.number.isRequired } // todo列表组件 class TodoList extends React.Component { render() { const {todos} = this.props return ( <ul> { todos.map((todo, index) => <li key={index}>{todo}</li>) } </ul> ) } } TodoList.propTypes = { todos: PropTypes.array.isRequired } // 渲染应用组件标签 ReactDOM.render(<App/>, document.getElementById(‘example‘)) </script> </body> </html>
原文地址:https://www.cnblogs.com/zhanzhuang/p/10710375.html
时间: 2024-09-30 04:25:05