初识React之组件创建和事件绑定

React创建组件的几种方法

  • ES5组件 React.createElement()
const element = React.createElement(
 'h1',    //标签名
 {className: 'greeting'},     //类名
 'Hello, world!'   //文本节点
);
  • 类组件 class User extends React.Component { }
class User extends React.Component {
  constructor(props) {
    super(props)
    // 当state发生变化时,视图自动变化(单向数据流)
    this.state = {
      msg: 'hello child'
    }
  }
  render() {
    return(
      <div>
        <h1>user page</h1>
      </div>
    )
  }
}
  • 无状态组件 function User(props) { }
function Child(props) {
  return (
    <div>
      <h1>user 子组件</h1>
      <span>{props.aaa}</span>
      <span>-</span>
      <span>{props.bbb}</span>
      <span>-</span>
      <span>{props.ccc}</span>
    </div>
  )
}
  • 高阶组件 function Hoc(Child) { }
  • Hocks 组件

事件绑定的几种方法

class User extends React.Component {
  constructor(props) {
    super(props)
    }
    this.click3 = this.click3.bind(this, '三')
  }
  // 实例方法
  click1(arg, e) {
    console.log('clicked 1', arg, this, e)
  }
  click2(arg, e) {
    console.log('clicked 2', arg, this, e)
  }
  click3(arg, e) {
    console.log('clicked 3', arg, this, e)
  }
  render() {
    return(
      <div>
        <h1>user page</h1>
        <div>
          {/* 注释:常用下面两种方式进行事件绑定 */}
          <button onClick={this.click1.bind(this, '一')}>点击事件1</button>
          <button onClick={(e)=>this.click2('二', e)}>点击事件2</button>
          {/* 注释:一般不建议这么写 */}
          <button onClick={this.click3}>点击事件3</button>
        </div>
      </div>
    )
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值