我想问一下当我做onclick事件时为什么我的状态没有改变.我刚才搜索过我需要在构造函数中绑定onclick函数,但状态仍未更新.这是我的代码:
import React from 'react';
import Grid from 'react-bootstrap/lib/Grid';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import BoardAddModal from 'components/board/BoardAddModal.jsx';
import style from 'styles/boarditem.css';
class BoardAdd extends React.Component {
constructor(props){
super(props);
this.state = {
boardAddModalShow: false
}
this.openAddBoardModal = this.openAddBoardModal.bind(this);
}
openAddBoardModal(){
this.setState({ boardAddModalShow: true });
// After setting a new state it still return a false value
console.log(this.state.boardAddModalShow);
}
render() {
return (
<Col lg={3}>
<a href="javascript:;" className={style.boardItemAdd} onClick={this.openAddBoardModal}>
<div className={[style.boardItemContainer,style.boardItemGray].join(' ')}>
Create New Board
</div>
</a>
</Col> …
Run Code Online (Sandbox Code Playgroud) class SomeClass extends Component{
someEventHandler(event){
}
render(){
return <input onChange={------here------}>
}
}
Run Code Online (Sandbox Code Playgroud)
我看到不同版本的------here------
部分.
// 1
return <input onChange={this.someEventHandler.bind(this)}>
// 2
return <input onChange={(event) => { this.someEventHandler(event) }>
// 3
return <input onChange={this.someEventHandler}>
Run Code Online (Sandbox Code Playgroud)
版本有何不同?或者只是一个偏好问题?
谢谢大家的回答和评论.都是有帮助的,我强烈建议阅读此链接FIRST如果你是这个困惑了我.
http://blog.andrewray.me/react-es6-autobinding-and-createclass/
我开始学习Vue.js和ECMA6语法,我在教程中看到了这一点:
methods: {
someMethod: function() {
console.log(this) // this works
}
}
Run Code Online (Sandbox Code Playgroud)
然后我认为语法可能是:
methods: {
someMethod: () => {
console.log(this) // this undefined
}
}
Run Code Online (Sandbox Code Playgroud)
但这有效:
methods: {
someMethod () {
console.log(this) // this works
}
}
Run Code Online (Sandbox Code Playgroud)
可以解释差异和ECMA5的语法吗?