javascript - 对react传参的困惑
本文介绍了javascript - 对react传参的困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
在看draft-js给的例子,出现了困惑。
平时传参我都是直接
xxx={(ev, arg1, arg2,……) => {this.xxx(ev, arg1, arg2,……)}
官方给出的快速开始例子
class MyEditor extends React.Component {
constructor(props) {
super(props);
this.state = {editorState: EditorState.createEmpty()};
this.onChange = (editorState) => this.setState({editorState});
}
render() {
return (
<Editor editorState={this.state.editorState} onChange={this.onChange} />
);
}
}
想知道editorState参数是怎么传给onChange这个函数的?
我试了
this.onChange = (editorState) => {
var length = arguments.length;
console.log('change');
for (var i = 0; i < length; i++) {
if (arguments[i] == editorState) {
console.log(i);
}
}
this.setState({editorState})
};
arguments中并没有editorState参数。而如果直接输出是有的
this.onChange = (editorState) => {
console.log(editorState);
this.setState({editorState})
};
为什么呢?
解决方案
箭头函数并不会创建新的 函数作用域, 所以 不会构建新的 this, 不能使用 arguments.
所以,题主写的测试 arguments
实际上不是你想要的 "arguments"
参考中文:
http://es6.ruanyifeng.com/#do...
箭头函数有几个使用注意点。
(1)函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。
(2)不可以当作构造函数,也就是说,不可以使用new命令,否则会抛出一个错误。
(3)不可以使用arguments对象,该对象在函数体内不存在。如果要用,可以用Rest参数代替。
(4)不可以使用yield命令,因此箭头函数不能用作Generator函数。
demo online: http://jsbin.com/yuforakeso/e...
demo:
function foo () {
const bar = function bar (arg1) {
console.log(`arguments:`);
console.log(arguments);
console.log(`bar arg1:${arg1}`)
}
bar('barArg');
const fooArguments = arguments;
const baz = (arg2) => {
console.log()
console.log(`arguments:`);
console.log(arguments);
if(fooArguments === arguments) {
console.log('Arrow Functions not have arguments');
}
console.log(`baz arg2:${arg2}`)
}
baz('bazArg');
}
foo()
这篇关于javascript - 对react传参的困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文