0
点赞
收藏
分享

微信扫一扫

React组件实例的三大核心属性

程序员知识圈 2022-02-18 阅读 84

目录

React组件实例的三大核心属性

state

初始化state

1.创建一个有状态的组件

<body>
    <div id="test"></div>
    <script type="text/babel">
        // 1.创建组件
        class Weather extends React.Component {
            constructor(props) {
                super(props);
                // 初始化状态
                this.state = { isHot: true };
            }
            render() {
                // 解构赋值
                const {isHot} = this.state;
                return <h1>今天天气很{isHot ? "炎热" : "寒冷"}</h1>
            }
        }
        // 2.渲染组件到页面
        ReactDOM.render(<Weather />, document.getElementById("test"))
    </script>
</body>

React中事件绑定

render() {
 // 解构赋值
 return <h1 onClick={this.changeWeather}></h1>
}
changeWeather() {
 console.log('今天天气真好!');
}

错误写法:

// 错误写法一
<h1 onClick='this.changeWeather'></h1>
// 错误写法二
<h1 onClick={this.changeWeather()}></h1>//这种写法会直接执行,相当于直接调用

类组件中自定义方法中this问题

 render() {
     // 解构赋值
     const { isHot } = this.state;
     return <h1 onClick={this.changeWeather}>今天天气很{isHot ? "炎热" : "寒冷"}</h1>
 }
 changeWeather() {
     console.log(this);// undefined
 }

在这里插入图片描述

解决类中this指向问题

  1. 在构造器中绑定this,this.changeWeather = this.changeWeather.bind(this)
<script type="text/babel">
    // 1.创建组件
    class Weather extends React.Component {
        constructor(props) {
            super(props);
            // 初始化状态
            this.state = { isHot: true };
            // 解决changeWeather中this指向问题
            this.changeWeather = this.changeWeather.bind(this)
        }
        render() {
            // 解构赋值
            const { isHot } = this.state;
            return <h1 onClick={this.changeWeather}>今天天气很{isHot ? "炎热" : "寒冷"}</h1>
        }
        changeWeather() {
            // changeWeather放在哪里? ———— Weather的原型对象上,供组件实例使用
            // 由于changeWeather是作为onClick的回调,所以不是通过实例调用,是直接调用
            // 类中的方法默认开启了局部的严格模式
            console.log(this);// undefined
        }
    }
    // 2.渲染组件到页面
    ReactDOM.render(<Weather />, test)
</script>
  1. 在回调函数中绑定this
<script type="text/babel">
    // 1.创建组件
    class Weather extends React.Component {
        constructor(props) {
            super(props);
            // 初始化状态
            this.state = { isHot: true };
            // 解决changeWeather中this指向问题
            // this.changeWeather = this.changeWeather.bind(this)
        }
        render() {
            // 解构赋值
            const { isHot } = this.state;
            // 解决changeWeather中this指向问题
            return <h1 onClick={this.changeWeather.bind(this)}>今天天气很{isHot ? "炎热" : "寒冷"}</h1>
        }
        changeWeather() {
            console.log(this);// undefined
        }
    }
    // 2.渲染组件到页面
    ReactDOM.render(<Weather />, test)
</script>
    <script type="text/babel">
        // 1.创建组件
        class Weather extends React.Component {
            constructor(props) {
                super(props);
                // 初始化状态
                this.state = { isHot: true };
                // 方法1:解决changeWeather中this指向问题
                // this.changeWeather = this.changeWeather.bind(this)
            }
            render() {
                // 解构赋值
                const { isHot } = this.state;
                // 方法2:解决changeWeather中this指向问题
                return <h1 onClick={this.changeWeather}>今天天气很{isHot ? "炎热" : "寒冷"}</h1>
            }
            // 方法:3:解决changeWeather中this指向问题
            changeWeather = () => {
                console.log(this);// undefined
            }
        }
        // 2.渲染组件到页面
        ReactDOM.render(<Weather />, test)
    </script>

通过setState方法修改状态(state)

<script type="text/babel">
    // 1.创建组件
    class Weather extends React.Component {
        constructor(props) {
            super(props);
            // 初始化状态
            this.state = { isHot: true };
            // 方法1:解决changeWeather中this指向问题
            // this.changeWeather = this.changeWeather.bind(this)
        }
        render() {
            // 解构赋值
            const { isHot } = this.state;
            // 方法2:解决changeWeather中this指向问题
            return <h1 onClick={this.changeWeather}>今天天气很{this.state.isHot ? "炎热" : "寒冷"}</h1>
        }
        // 方法:3:解决changeWeather中this指向问题
        changeWeather = () => {
            const isHot = this.state.isHot;
            // 更新状态
            this.setState({
                isHot: !isHot
            })
            console.log(this.state.isHot);// undefined
        }
    }
    // 2.渲染组件到页面
    ReactDOM.render(<Weather />, test)
</script>

state的简写代码

 // 1.创建组件
class Weather extends React.Component {
    // 初始化状态
    state = { isHot: true };
    render() {
        const { isHot } = this.state;
        return <h1 onClick={this.changeWeather}>今天天气很{this.state.isHot ? "炎热" : "寒冷"}</h1>
    }
    // 自定义方法
    changeWeather = () => {
        const isHot = this.state.isHot;
        this.setState({
            isHot: !isHot
        })
    }
}
// 2.渲染组件到页面
ReactDOM.render(<Weather />, test)

props

props的基本使用

<body>
    <div id="test"></div>
    <script type="text/babel">
    class Person extends React.Component{
        render(){
        	console.log(this.props);
            return (
                <ul>
                    <li>姓名:{this.props.name}</li>
                    <li>性别:{this.props.sex}</li>
                    <li>年龄:{this.props.age}</li>    
                </ul>
            )
        }
    }
    ReactDOM.render(<Person name="江流" age={19} sex="男"/>, document.getElementById("test"))
    </script>
</body>

在这里插入图片描述

批量传递props

 class Person extends React.Component {
     render() {
         console.log(this.props);
         return (
             <ul>
                 <li>姓名:{this.props.name}</li>
                 <li>性别:{this.props.sex}</li>
                 <li>年龄:{this.props.age}</li>
             </ul>
         )
     }
 }
 const p = { name: "江流", age: 19, sex: "男" }
 ReactDOM.render(<Person {...p}/>, document.getElementById("test"))//这里的{...p}不是使用的扩展运算符,是在babel环境下传参的一种方式,只能在标签传参里面使用

props进行类型限制

 <script type="text/babel">
     class Person extends React.Component {
         static propTypes = {
             name: PropTypes.string.isRequired, //限制name必传,且为字符串
             sex: PropTypes.string, //限制sex为字符串
             age: PropTypes.number, //限制age为数值
             speak: PropTypes.func, //限制speak为函数
         }
         static defaultProps = {
             sex: "男", //sex默认值为男
             age: 18, //age默认值为18
         }
         render() {
             console.log(this.props);
             return (
                 <ul>
                     <li>姓名:{this.props.name}</li>
                     <li>性别:{this.props.sex}</li>
                     <li>年龄:{this.props.age}</li>
                 </ul>
             )
         }
     }

     function speak() {
         console.log("我是谁?");
     }
     const speak2 = 1;
     ReactDOM.render(<Person name="江流儿" speak={speak} />, document.getElementById("test"))// 这里的...不是构造字面量
 </script>

props与构造器

 constructor(props){
     super(props)
 }

refs

字符串形式的ref

class Demo extends React.Component {
            showData = () => {
                const { input1 } = this.refs;
                alert(input1.value);
            }
            render() {
                return (
                    <div>
                        <input type="text" ref='input1' />
                        <button onClick={this.showData}>点我</button>
                    </div>
                )
            }
        }
        ReactDOM.render(<Demo />, document.getElementById("test"))

回调形式ref

 class Demo extends React.Component {
     showData1 = () => {
         const { input1 } = this;
         alert(input1.value);
     }
     showData2 = () => {
         const { input2 } = this;
         alert(input2.value);
     }
     render() {
         console.log(this.refs);
         return (
             <div>
                 <input type="text" ref={currentNode => this.input1 = currentNode} />
                 <button onClick={this.showData1}>点我</button>

                 <input type="text" ref={currentNode => this.input2 = currentNode} />
                 <button onClick={this.showData2}>点我</button>
             </div>
         )
     }
 }
 ReactDOM.render(<Demo />, document.getElementById("test"))

createRef形式

  class Demo extends React.Component {
      myRef1 = React.createRef();
      myRef2 = React.createRef();
      showData1 = () => {
          alert(this.myRef1.current.value);
      }
      showData2 = () => {
          alert(this.myRef2.current.value);
      }
      render() {
          console.log(this.refs);
          return (
              <div>
                  <input type="text" ref={this.myRef1} />
                  <button onClick={this.showData1}>点我</button>

                  <input type="text" ref={this.myRef2} />
                  <button onClick={this.showData2}>点我</button>
              </div>
          )
      }
  }
  ReactDOM.render(<Demo />, document.getElementById("test"))

事件处理

举报

相关推荐

0 条评论