组件的三大属性state,props,refs与事件处理

时间:2023-03-08 17:37:09
组件的三大属性state,props,refs与事件处理

组件的三大属性state

state是组件对象最重要的属性, 值是对象(可以包含多个数据),组件被称为"状态机", 通过更新组件的state来更新对应的页面显示(重新渲染组件)

初始化指定

constructor() {
    super()
    this.state = {
        stateName1 : stateValue1,
        stateName2 : stateValue2
    }
}

读取显示

this.state.stateName1

更新状态-->更新界面(自动更新)

this.setState({stateName1 : newValue})

需求:自定义组件, 功能说明如下:

显示h2标题, 初始文本为: 你喜欢我,点击标题更新为: 我喜欢你

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>07_component_state</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/babel.min.js"></script>
<script type="text/babel">
  /*
  需求: 自定义组件, 功能说明如下
    1. 显示h2标题, 初始文本为: 你喜欢我
    2. 点击标题更新为: 我喜欢你
  */
  // 1.定义组件
  class Like extends React.Component {
    constructor(props) { // 初始化状态
      super(props)
      this.state = {
        isLikeMe : false
      }

      // 将新增的方法的this强制绑定为组件对象
      this.handleClick = this.handleClick.bind(this) //
    }
    // 这个是重写组件内的方法,所以this代表的是组件对象
    render () {
      // 读取状态,最终要得到isLikeMe的值
      // const isLikeMe = this.state.isLikeMe // 正常写法
      const {isLikeMe} = this.state // 解构赋值的写法(es6的语法)
      return <h2 onClick={this.handleClick}>{isLikeMe?'你喜欢我' : '我喜欢你'}</h2>
    }

    // 新添加的方法,内部的this默认不是组件对象,而是undefined
    handleClick () {
      const isLikeMe = !this.state.isLikeMe
      // 更新状态
      this.setState({isLikeMe})
    }
  }

  // 2.渲染组件
  ReactDOM.render(<Like/>, document.getElementById('example'))
</script>
</body>
</html>

组件的三大属性props

每个组件对象都会有props(properties的简写)属性,组件标签的所有属性都保存在props中,所有组件标签的属性的集合对象

作用:通过标签属性从组件外向组件内传递变化的数据 ,注意: 组件内部不要修改props数据

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>04_component_props</title>
</head>
<body>

<div id="example1"></div>
<div id="example2"></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/babel.min.js"></script>
<script type="text/babel">
  // 1.定义组件
  function Person(props) {
    return (
      <ul>
        <li>姓名:{props.name}</li>
        <li>年龄:{props.age}</li>
        <li>性别:{props.sex}</li>
      </ul>
    )
  }

  // 2.渲染组件标签
  const p1 = {
    name: 'lina',
    age: 18,
    sex: '女'
  }
  ReactDOM.render(<Person name={p1.name} age={p1.age} sex={p1.sex}/>, document.getElementById('example1'))
</script>
</body>
</html>

内部读取某个属性值

对props中的属性值进行类型限制和必要性限制,使用比较新的react版本,需要引入prop-types.js这个文件

// 对props中的属性值进行类型限制和必要性限制
  Person.propTypes = {
    name: PropTypes.string.isRequired, // name属性的值必须是字符串并且必须要传,如果有默认值就不会报错
    age: PropTypes.number.isRequired
  }

扩展属性: 将对象的所有属性通过props传递

// ...的作用:一种是打包(就是将一组数据打包到一起),一种是解包()
  ReactDOM.render(<Person {...p1}/>, document.getElementById('example1'))

默认属性值

// 指定属性的默认值
  Person.defaultProps = {
    age: 18,
    sex: '男'
  }

组件类的构造函数

class Person extends React.Component {
    render () {
      return (
        <ul>
          <li>姓名:{this.props.name}</li>
          <li>年龄:{this.props.age}</li>
          <li>性别:{this.props.sex}</li>
        </ul>
      )
    }
  }

需求: 自定义用来显示一个人员信息的组件
1). 如果性别没有指定, 默认为男
2). 如果年龄没有指定, 默认为18

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>04_component_props</title>
</head>
<body>

<div id="example1"></div>
<div id="example2"></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/babel.min.js"></script>
<script type="text/javascript" src="../js/prop-types.js"></script>
<script type="text/babel">
  // 1.定义组件
//  function Person(props) {
//    return (
//      <ul>
//        <li>姓名:{props.name}</li>
//        <li>年龄:{props.age}</li>
//        <li>性别:{props.sex}</li>
//      </ul>
//    )
//  }

  class Person extends React.Component {
    render () {
      return (
        <ul>
          <li>姓名:{this.props.name}</li>
          <li>年龄:{this.props.age}</li>
          <li>性别:{this.props.sex}</li>
        </ul>
      )
    }
  }

  // 指定属性的默认值
  Person.defaultProps = {
    age: 18,
    sex: '男'
  }

  // 对props中的属性值进行类型限制和必要性限制
  Person.propTypes = {
    name: PropTypes.string.isRequired, // name属性的值必须是字符串并且必须要传
    age: PropTypes.number.isRequired
  }

  // 2.渲染组件标签
  const p1 = {
    name: 'lina',
    age: 18,
    sex: '女'
  }
  const p2 = {
    name: 'jack',
    age: 13,
    sex: '男'
  }

  // ...的作用:一种是打包(就是将一组数据打包到一起),一种是解包()
  ReactDOM.render(<Person {...p1}/>, document.getElementById('example1'))
  ReactDOM.render(<Person name={p2.name} age={p2.age}/>, document.getElementById('example2'))
</script>
</body>
</html>

组件的三大属性refs

通过ref获取组件内容特定标签对象, 进行读取其相关数据

<input type="text" ref="content"/> // 绑定ref

const input = this.refs.content  // 获取ref

上面这个写法官方不建议这么写,可以使用下面这种,回调函数在组件初始化渲染完或卸载时自动调用,在组件中可以通过this.msgInput来得到对应的真实DOM元素

<input type="text" ref={input => this.msgInput = input}/> // 绑定ref

alert(this.msgInput.value) // 获取ref
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>07_component_refs</title>
</head>
<body>
<br>
  <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/babel.min.js"></script>

  <script type="text/babel">
    /*
    需求: 自定义组件, 功能说明如下:
      1. 界面如果页面所示
      2. 点击按钮, 提示第一个输入框中的值
   */

    // 1. 定义组件
    class Mycomponent extends React.Component {
      constructor (props) {
        super (props)
        this.showInput = this.showInput.bind(this)
      }
      showInput () {
        alert(this.msgInput.value)
      }

      render () {
        return (
          <div>
            <input type="text" ref={input => this.msgInput = input}/>&nbsp;
            <button onClick={this.showInput}>提示输入</button>&nbsp;
          </div>
        )
      }
    }

    // 2. 渲染组件标签
    ReactDOM.render(<Mycomponent/>, document.getElementById('example'))
  </script>
</body>
</html>

组件中的事件处理

通过onXxx属性指定组件的事件处理函数(注意大小写)

React使用的是自定义(合成)事件, 而不是使用的原生DOM事件 ,React中的事件是通过事件委托方式处理的(委托给组件最外层的元素)

onXxx={this.eventHandler}

在组件中添加事件处理方法,通过event.target得到发生事件的DOM元素对象

eventHandler(event) {}
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>07_component_refs</title>
</head>
<body>
<br>
  <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/babel.min.js"></script>

  <script type="text/babel">
    // 1. 定义组件
    class Mycomponent extends React.Component {
      constructor (props) {
        super (props)
        this.handleBlur = this.handleBlur.bind(this)
      }

      handleBlur (event) {
        alert (event.target.value)
      }

      render () {
        return (
          <div>
            <input type="text" placeholder="失去焦点提示内容" onBlur={this.handleBlur}/>
          </div>
        )
      }
    }

    // 2. 渲染组件标签
    ReactDOM.render(<Mycomponent/>, document.getElementById('example'))
  </script>
</body>
</html>