React 开发中的几个注意点

来源:互联网 发布:集团公司网络规划 编辑:程序博客网 时间:2024/06/10 01:15

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>  );}
0 0