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