作用域问题反应父子方法ES6
Scoping issue react parent-child method ES6
我目前有点拘泥于以下内容。
function Tag(props){
let {text, onRemove, key} = props;
return (
<span onClick={onRemove(key)} key={key}>{text}</span>
)
}
function TagInput (props) {
let {onChange, value, onKeyDown} = props;
return (
<input type="text" onChange={onChange} value={value} onKeyDown={onKeyDown} />
)
}
class TagsInput extends Component {
render() {
let { Tag, TagInput, state } = this.props;
console.log(state.tags);
return (
<div ref="div" onClick={(e) => this.handleClick(e)}>
{state.tags.map((tag) =>
<Tag
text={tag.text}
key={tag.id}
onRemove={this.handleRemove}
/>
)}
<TagInput
onChange={(e) => this.handleChange(e)}
onKeyDown={(e) => this.handleKeyDown(e)}
/>
</div>
)
}
handleClick(e) {
console.log(e.target.value);
}
handleChange(e){
//console.log(e.target.value);
}
handleKeyDown(e){
//console.log('keycode', e.keyCode);
const { dispatch } = this.props;
if (e.keyCode === 32) {
dispatch(addTag(e.target.value));
}
if (e.keyCode === 8 && e.target.value.length === 0) {
dispatch(removeTag());
}
}
handleRemove(id){
const { dispatch } = this.props;
dispatch(removeTag(id));
}
}
TagsInput.propTypes = {
TagInput: React.PropTypes.func,
Tag: React.PropTypes.func,
removeKeyCodes: React.PropTypes.array,
addKeyCodes: React.PropTypes.array
};
TagsInput.defaultProps = {
TagInput: TagInput,
Tag: Tag,
removeKeyCodes: [8],
addKeyCodes: [9, 13]
};
我在控制台Uncaught TypeError: Cannot read property 'props' of undefined
中从方法handleRemove
的const { dispatch } = this.props
行得到以下错误。这似乎是一个范围界定问题,但我似乎无法理解为什么会发生这种情况(并非双关语lol)。
ES6类不会自动将this
绑定到函数,但扩展Component
提供的函数除外,如componentDidMount
等。
来自文档
ES6方式-将this
绑定到构造函数中的方法,或者调用它们的位置:
class TagsInput extends Component {
constructor (props) {
super(props)
this.handleRremove = this.handleRemove.bind(this)
}
OR
render() {
return (
<Tag
onRemove={this.handleRemove.bind(this)}
/>
}
ES7方式#1:绑定语法
this.handleRemove = ::this.handleRemove
ES7方法#2:类箭头函数(我认为这是最好的方法):
handleRemove = (id) => {
const { dispatch } = this.props;
dispatch(removeTag(id));
}
然后称之为:
onRemove={ () => this.handleRemove(tag.id) }
更新:阅读@Road的答案。在使用点绑定方法时,需要传递参数。
您尝试过绑定this
吗?尝试this.handleRemove.bind(this, tag.id)
。tag.id
是您传递的参数,因为handleRemove(id)
需要一个id
作为参数。
相关文章:
- javascript从子方法调用父方法
- JS对象文字中的方法和子方法
- 从子方法访问父对象
- 如何从子方法调用父方法
- 在 dojo 中使用它通过父类访问子方法
- 带有构造函数的Javascript子方法/名称空间
- 作用域问题反应父子方法ES6
- 删除变量's的价值而不丢失其子方法
- 用子方法实现函数可以吗
- 我如何从父调用原型子方法
- 从子方法访问父属性
- 带有子方法的方法链接
- 自动css选择器生成的第n子方法的替代方案
- 在Javascript中从子方法调用父方法
- 在JavaScript中从父方法调用子方法
- 如何从子方法中分离父函数
- jQtree,调用嵌套列表中的方法调用父方法和子方法
- Javascript Prototype pub子方法超出作用域
- 父对象调用子方法
- React 中的哪种绑定上下文方法(ES6 类)更好