React专题2: 创建组件和事件绑定

2020-02-06  本文已影响0人  ImmortalSummer

react 的两个重点: 组件 和 状态(可用的变量)

封装组件

           class Comp1 extends React.Component{
                // 该方法 必须实现
                render(){
                    return <span>你好,我叫{this.props.name},我今年{this.props.age}岁了</span>
                }
            }
            var div2 = document.getElementById("div2");
            ReactDOM.render(
                <Comp1 name="小明" age="12"/>,
                div2
            )

讲解

  1. 组件中必须实现render()方法
  2. react中可以通过{变量}来将变量和字符串组合在一起
  3. this.props.属性名可以访问到组件设置的属性

事件绑定与react状态

               class Comp2 extends React.Component{
                constructor(...args){
                    super(...args);
                    this.state = {userName:""}
                }
                changeHandle(ev){
                    // 不能直接使用this, 需要是用ev.target做一下临时传递
                    // console.log(ev.target.value);
                    this.setState({
                        userName:ev.target.value
                    })
                }
                render(){
                    return <div>
                        <input type="text" onChange={this.changeHandle.bind(this)}/>
                        <span>{this.state.userName}</span>
                        </div>;
                }
            }
            var div3 = document.getElementById("div3");
            ReactDOM.render(
                <Comp2/>,
                div3
            )

讲解

1.state是变量
在构造函数中赋值时 this.state = {key:value}
在其他方法中更改时 this.setState({key:value})

  1. React对大小写敏感, 注意事件名称的大小写

  2. React中绑定事件
    onClick={this.func.bind(this)}
    注意:funcs使用箭头函数写则不需要绑定this, 因为箭头函数的this是固定的

  3. 用构造函数constructor时必须调用super, 并将入参全部传递给super

上一篇 下一篇

猜你喜欢

热点阅读