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
- React 开发中的几个注意点
- React学习中几个注意点
- React学习中几个注意点
- EL 表达式学习中的 几个注意点。
- java中的几个循环的注意点
- Mybatis分页实现中的几个注意点
- ActionScript 3 开发的几个注意点
- Java开发的几个注意点
- Java开发的几个注意点
- hybird app 开发的几个注意点
- NSIS插件开发的几个注意点
- Java开发的几个注意点
- Java开发的几个注意点
- 开发中的一些注意点
- Android 开发中的注意点
- PathAppend几个注意点
- 论敏捷开发中的注意点
- IOS开发中的实用技术使用注意点
- Web服务器、容器、Servlet分别干什么?
- 8086汇编常见问题及解决方案
- C++ 实现tring字符串trim函数和split函数
- 一次奇妙的大项目维护经历(1)
- 大奖赛现场统分
- React 开发中的几个注意点
- J2EE的组成。
- 欢迎使用CSDN-markdown编辑器
- 10.字符设备驱动模型(2)-字符设备驱动模型
- opencv最小包络三角形
- TensorFlow基本用法
- 社交网络 (并查集的应用)
- 促销活动 (优先队列的应用)
- 如何运用归并排序快速求得逆序对数目