React 基础篇学习

react 基础篇学习

JSX

  1. 标签即js变量
  2. 使用 {msg} 包裹变量
  3. 标签属性也可以使用变量 <img name={tutu} / >

元素渲染

 

const element = <h1>haha</h1> reactDom.render( element, document.getElementById('root') )

只有调用reactDom.render才会重新渲染

组件

  1. 函数组件
 

function hello(props){ return <h2>你好, props.name<h2> }

  1. class组件(使用props的时候需要加this)

class Hello extends React.Compenent { return <h2>你好, this.props.name<h2> }

  1. props是只读的

如何使用state

 

class Clock extends ReactCompenent { constructor(props){ super(props) this.date = {date: new Date()} } componentDidMount(){ this.timerId = setInterval( ()=>this.tick() ) } compenentwillunmount(){ clearInterval(this.timeID) } tick(){ this.setSate({ date: new Date() }) } render(){ return <h2>it is {this.state.date.toLocaleTimeString()}<h2> } }

  1. 在更改state的数据时,不能直接更改(this.state.date = '...),需要使用this.setState({date: '....'})
  2. this.setState({ date: '...' })是可以合并对象的,只单独对某个属性做更改就可以合并到原对象上去
  3. 异步更新
 

// Wrong this.setState({ counter: this.state.counter + this.props.increment, }); // Correct this.setState((state, props) => ({ counter: state.counter + props.increment }));

事件处理

  1. 如果是函数组件,直接使用JSX语法调用即可
 

<button onclick={handleClick}> function handleclick() { alert('hi') }

  1. 如果是class组件,一定要注意this问题,绑定this的方式有如下三种
 

constructor(props) { super(props); this.state = {isToggleOn: true}; // 为了在回调中使用 `this`,这个绑定是必不可少的 this.handleClick = this.handleClick.bind(this); } render() { return ( <button onClick={this.handleClick}> {this.state.isToggleOn ? 'ON' : 'OFF'} </button> ); }

 

class LoggingButton extends React.Component { // 此语法确保 `handleClick` 内的 `this` 已被绑定。 // 注意: 这是 *实验性* 语法。 handleClick = () => { console.log('this is:', this); } render() { return ( <button onClick={this.handleClick}> Click me </button> ); } }

 

class LoggingButton extends React.Component { handleClick() { console.log('this is:', this); } render() { // 此语法确保 `handleClick` 内的 `this` 已被绑定。 return ( <button onClick={() => this.handleClick()}> Click me </button> ); } }

条件渲染

  1. 可以通过条件运算符&&写到JSX表达式中从而控制是否渲染
  2. 三目运算符同理
  3. 通过if else 写两个状态组件也可以

列表&key

 

class hello extends React.Compenent { constructor(props){ super(props) this.state = { msg: '你好', number:[1,2,3,4,5] } } render(){ const lists = this.state.numbers.map((num)=>{ <li key={num.toString()}>this is number:{num}</li> }) return( <ul> {lists} </ul> ) } }

表单

组合继承(相当于vue中slot)

  1. 使用children这个特殊的prop
 

function hello(props){ return ( <div> <h2>{props.msg}</h2> {props.children} </div> ) } function welcome(props){ return { <hello msg='hello,tutu'> <p>welcome~~<p> </hello> } } ReactDom.render( <welcome />, document.getElementById('root') )

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值