KinoOfficial / ReactCourse

0 stars 0 forks source link

React基础和组件,map遍历组件 #1

Open KinoOfficial opened 1 year ago

KinoOfficial commented 1 year ago

用map函数遍历ul li:

const arr=[1,2,3,4,5,6,7,8,9,10,11,12] return (

    {arr.map((item,index)=>{ return (
  • {item}
  • ) //输出12个内容为1-12的li })}

);

KinoOfficial commented 1 year ago

函数式组件和props

function App() { const arr=[1,2,3,4,5,6,7,8,9,10,11,12] return (

this is app
{}

); }

function Children(props){ return(

Children data is {props.name}

) }

// 输出结果 this is app // Children data is Kino

KinoOfficial commented 1 year ago

类组件

props : 用this.props

import React, { Component } from 'react'

class Child extends Component { render() { return (

child data is {this.props.name}
)

} }

export default class App extends Component { render() { return (

this is main
)

} }

props.children 通过 props.children在子组件中间添加内容

import React, { Component } from 'react'

class Child extends Component { render() { console.log(this.props.children) return (

{this.props.children[0]} child data is {this.props.name} {this.props.children[1]}
)

} }

export default class App extends Component { render() { return (

this is main
this is the first child
this is the second child
)

} } // //输出结果为 this is main // this is the first child // child data is Kino // this is the second child

KinoOfficial commented 1 year ago

类组件的state 赋值 this.state={属性名:属性值}

修改state属性的setState方法 this.setState{属性名:新的属性值}

setState 是异步 循环执行会集中只执行一次 解决办法 setState((prevState)=>{ //执行内容 return {当前循环的state属性:当前变化的state属性值} })

如果是我想在state更新之后⽴⻢拿到最新的数据进⾏后续操作应该怎么办? setState接受第⼆个参数,即状态更新后的回调函数 fn = () => { this.setState({ info:this.state.info+1 },()=>{ alert(this.state.info) }) }. //在第二个参数上设为函数并执行需要执行的内容

KinoOfficial commented 1 year ago

组件的父子传值

父到子:简单props传递 子到父 :父组件建立一个函数A用于setState传到自己的state,并将A通过props传到子组件,子组件创建B函数并通过事件去执行该函数(A为主要核心)

子到父案例:

Githubissues.
  • Githubissues is a development platform for aggregating issues.