React学习日记5


020 props基本使用

使用props传值,在标签里面直接添加对应属性就可以了


024 类式组件中的构造器与props

类中的构造器如果不省略,

构造器是否接受props,是否传递给super,取决于是否希望在构造器中通过this访问props(几乎不用)

开发的时候还是几乎不写构造器。。。

025 函数式组件使用props

function Person(props){
      // 以对象的形式进行收集
      console.log(props);
      const {name,sex,age} = props
      return (
          
  • name:{name}
  • sex:{sex}
  • age:{age}
) } ReactDOM.render(,document.getElementById('test'))

函数式组件只能玩props,不能用state和refs

026 总结props


027 字符串形式的refs

组件里面的ref相当于给组件打一个表示 类似于id

this.refs相当于拿到一个对象

字符串的形式refs已经不常用了

class Demo extends React.Component{
    render(){
      return (
        
     
) } showData = ()=>{ // 这里拿到的真实DOM // console.log(this.refs.input1); const {input1} = this.refs alert(input1.value) } showData2 = ()=>{ const {input3} = this.refs alert(input3.value) } } ReactDOM.render(, document.getElementById('test'))

028-029 回调形式的refs

render(){
      return ( //  ref 属性值为一个回调函数 渲染的时候自动执行,使用箭头函数,参数为实例本身。this指向render作用域
              //   将input1 放入实例中
        
{this.input1 = currentNode}} type="text" placeholder = "点击按钮提示数据"/>    this.input3 = currentNode}onBlur={this.showData2} type="text" placeholder = "渲染组件到页面"/> 
) } showData = ()=>{ const {input1} = this alert(input1.value) } showData2 = ()=>{ const {input3} = this alert(input3.value) } }

ref 属性值为一个回调函数 渲染的时候自动执行,使用箭头函数,参数为实例本身。this指向render作用域

如果ref回调函数是以内联函数的方式的定义的,在更新(render)的过程当中它会被执行两次,第一次传入参数null,第二次才真正传入结点【这一点这个不重要】,可以写成下面的形式规避这个问题

render(){
        const {isHot} = this.state
        return (
          

今天天气很{isHot?'炎热':'凉爽'}

{/*{this.input1 = c;console.log('@',c);}}/>*/}
) }

030 create refs

class Demo extends React.Component{
    // 该容器只能存一个,专人专用
    myRef = React.createRef()
    myRef2 = React.createRef()
    render(){
      return ( 
        
     
) } showData = ()=>{ console.log(this.myRef); } showData2 = ()=>{ console.log(this.myRef2.current.value); } }

React.createRef()创建一个容器,这个容器只能容纳一个ref

031 总结 refs

  1. 尽量避免使用字符串形式的ref 有bug
  2. 回调形式的ref稍微麻烦点 (开发常用)
  3. createRef (最为推荐