码迷,mamicode.com
首页 > 其他好文 > 详细

React开发时候注意点

时间:2018-08-07 20:48:25      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:==   cto   author   reac   ons   use   info   .text   col   

JSX

  1. 使用jsx的使用,用一个{}包裹起来,例如

    const method = {<div> 123 </div>}


  2. 使用()小括号,防止分号自动插入

    const element = 
    (
    
      <h1>
    
        Hello, {formatName(user)}!
    
      </h1>
    
    );
    

      

  3. 如果使用箭头函数,返回的是一个对象的话,使用()包围起来

    const element = 
    (
    
      <h1>
    
        Hello, {formatName(user)}!
    
      </h1>
    
    );
    

      

    组件数据传递

  4. 通过props

    function Comment(props) {
      return (
    
        <div className="Comment">
    
          <div className="UserInfo">
    
            <Avatar user={props.author} />
    
            <div className="UserInfo-name">
    
              {props.author.name}
    
            </div>
    
          </div>
    
          <div className="Comment-text">
    
            {props.text}
    
          </div>
    
          <div className="Comment-date">
    
            {formatDate(props.date)}
    
          </div>
    
        </div>
    
      );
    
    }
    

      

    这样的话,就可以通过prop获得到数据,这个数据是只读的,不要修改
    
  5. 子组件向父组件传递数据

    父:
    bindValue = (e) => { console.log(e)}
    
    <Son onChange = {this.bindValue}>
    
    子:
    
    <input onChange={this.props.onChange}>
    
    这样的话,子--->父 传递便实现了
    

      

    State

  6. constructor可以初始化state

    父:
    bindValue = (e) => { console.log(e)}
    
    <Son onChange = {this.bindValue}>
    
    子:
    
    <input onChange={this.props.onChange}>
    
    这样的话,子--->父 传递便实现了
    

      

  7. 取得state的值,通过 this.state.date

  8. 改变state,通过 this.setState({}),不要忘记里面要使用{}的方式

  9. 注意事项

    (1)修改方式
    
    // Wrong,页面不会重新渲染
    this.state.comment = ‘Hello‘;
    
    // Correct
    
    this.setState({comment: ‘Hello‘});
    (2)更新是异步的,有时候通过setState设置数据后,打印,输出的值是不对的
    

      

    绑定函数

    由于this默认是不会绑定到Es6类中的,有几种方法

  10. constructor中设置

     constructor (props) {
        super(props)
    
        this.handleClick = this.handleClick.bind(this)
    
    }
    

      

  11. 使用箭头函数

    handClick = () => {this.handClick()}
    不要忘记了后面加入(),得让函数运行,这样的话还一传递参数,如下:
    
    handClick = (e) => {this.handClick(e)}
    

      

    条件渲染

  12. 控制显示和隐藏的时候可以使用 &&

    const show = 1
    show === 1 && <div>hello React </div>
    
    这样就可以控制是否显示,可以通过一个事件控制show的值

     

  13. 三元表达式

    show ? (<div key=‘1‘> show</div>): (<div key=‘2‘> hidden </div>)
    最后加key,因为页面在渲染的时候会利用重复的元素,不是每一个都要重复渲染,加入key           
    
    就会认为是不同的元素
    

      

React开发时候注意点

标签:==   cto   author   reac   ons   use   info   .text   col   

原文地址:https://www.cnblogs.com/felearn/p/React-kai-fa-shi-hou-zhu-yi-dian.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!