react简单入门教程(Todolist实现 )
- 2020 年 1 月 20 日
- 筆記
1.创建一个react项目
创建一个react:打开命令行输入以下命令
npx create-react-app todolist(项目名字)
进入项目目录
cd todolist
启动项目
npm start
浏览器输入
localhost:3000
2.组件定义
class App extends React.Component{ render() { return ( <div className="App"> hello,十月梦想! 第一个react小程序! </div> ); } } //导出组件 export default App
引用组件
在入口文件中使用import导入 import App from './App';
3.简单jsx语法
class App extends React.Component{ render() { return ( <div className="App"> //jsx语法可以使用花括号使用js表达式,但不能使用js语句 {1+1} hello,十月梦想! 第一个react小程序! </div> ); } }
4.执行函数
第一种是现在定义一个函数,然后使用click调用 <button onClick={this.handlebtnClick.bind(this)} >Add</button> 第二种可以直接在标签内使用语法 <button onClick={ ()=>{ alert('哎哟,你点击了我一下') } } >Add</button>
5.数据流存放
在class类之后定义构造函数, constructor(props) { super(props); //定义的数据存放为对象形式 this.state = { list: [ 'learn English', 'learn Math', 'learn java' ] } }
注意:点击对象获得state内容,可以在指定函数后加上.bind(this)进行绑定,此时可以去表示state
this.handlebtnClick.bind(this)
6.react循环标签
//map进行bainli遍历 this.state.list.map((item,index)=>{ return <li key={index}> {item}</li> })
7.父子组件通讯
父组件传递:使用属性content传给子组件 return <Todoitem key={index} content={item} /> 子组件使用props.content接收 return <li > {this.props.content}</li>
8.子父组件通讯
//子组件 子组件向父组件传递:使用一个方法向父组件传递 render(){ return <li onClick={this.handleDelete.bind(this)}> {this.props.content}</li> } 子组件定义的方法 handleDelete(){ this.props.delete(this.props.index) } //父组件 定义一个方法接收子组件的传递 return <Todoitem key={index} content={item} delete={this.handleDelete.bind(this,index)} index={index} /> 父组件的方法 handleDelete(index){ const list=[...this.state.list]; list.splice(index,1) this.setState({ list }) }
本博客所有文章如无特别注明均为原创。作者:十月梦想 ,复制或转载请以超链接形式注明转自 十月梦想博客 。 原文地址《react简单入门教程(Todolist实现 )》