React 开发中的几个注意点

1. this is undefined

参考问题http://stackoverflow.com/questions/33973648/react-this-is-undefined-inside-a-component-function
当你用es6语法写react的时候,用以下方法绑定事件,会发现this指针undefined,此时会抛出setState is not a function 错误,原因是采用es6写法,react没有帮你自动注入this,而如果你采用React.createClass,则帮你自动注入this,不会出现这种错误

class PlayerControls extends React.Component {
  constructor(props) {
    super(props);
    this.state={
        loopActive:false
    };
  }
  onToggleLoop(event) {
    // "this is undefined??" <--- here
    this.setState({loopActive: !this.state.loopActive});
  }
  render() {
    return (
      <div className="player-controls">
        <a
          className="player-control-icon"
          onClick={this.onToggleLoop}
        />
        test
        </a>
      </div>
    );
  }

解决方案:
1.使用箭头函数

<a className="player-control-icon" onClick={(e)=>this.onToggleLoop(e)}/>test</a>

2.在constructor注入this

constructor(props) {
    super(props);
    this.state={
        loopActive:false
    };
    this.onToggleLoop = this.onToggleLoop.bind(this);
  }

3.在绑定事件的时候,注入this

<a className="player-control-icon" onClick={this.onToggleLoop.bind(this)}/>test</a>

4.使用React.createClass方式创建组件

5.使用一些自动绑定this 的装饰器库

2. 阻止事件冒泡

e.stopPropagation() 来阻止事件冒泡到 document,这时候是行不通的,参见 Event delegation,因为 e.stopPropagation 是内部“合成事件” 层面的,解决方法是要用 e.nativeEvent.stopImmediatePropagation();
e.preventDefault();可以正常使用

3.渲染列表需要绑定key id

function ListItem(props) {
  // Correct! There is no need to specify the key here:
  return <li>{props.value}</li>;
}

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    // Correct! Key should be specified inside the array.
    <ListItem key={number.toString()}
              value={number} />
  );
  return (
    <ul>
      {listItems}
    </ul>
  );
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值