[英]HandleChange in Javascript with React and Semantic Ui
const languageOptions = [
{ key: '0', text: 'English', value: 'english' },
{ key: '1', text: 'Portuguese', value: 'portuguese' },
]
handleChange = field => (e, { value }) => {
this.setState({[field]:value})
}
//what is difference between this functions?
handleChange = field => event => {
this.setState({[field]:event.target.value})
}
<Input onChange={this.handleChange('language')} options={languageOptions} value={this.state.language} />
I do not understand why that second handleChange doesn't work, can anyone explain? 我不明白为什么第二个handleChange不起作用,有人可以解释吗? I usually use the second way (with the handleChange ('location')
), but it does not work ... What does (e, {value})
mean? 我通常使用第二种方法(使用handleChange ('location')
),但是它不起作用... (e, {value})
是什么意思?
handleChange = (e, { value })
can also be written as handleChange = (e, valueObject)
where valueObject is {value: 'YOUR_VALUE_HERE'}
. handleChange = (e, { value })
也可以写成handleChange = (e, valueObject)
,其中valueObject是{value: 'YOUR_VALUE_HERE'}
。
This is called object deconstructing and you can read more about it here . 这称为对象解构,您可以在此处了解更多信息。
In order to get your code working the way that you want it to you will have to modify your handleChange
function to be the following: 为了使代码按您希望的方式工作,您必须将handleChange
函数修改为以下内容:
handleChange = field => (event, { value }) => {
this.setState({[field]: value})
}
Really good question! 真是个好问题! Let me try to explain. 让我尝试解释一下。
In your first function 在你的第一个功能
handleChange = (e, { value }) => {
this.setState({same:value})
}
your function is accepting e
and {value}
as function parameter. 您的函数接受e
和{value}
作为函数参数。 however your second function is 但是你的第二个功能是
concise body syntax, where in the "return" is function body. 简洁的主体语法,其中“返回”是函数主体。 So every expression after => is a function. 因此,=>之后的每个表达式都是一个函数。 This is the typical example of
Currying
这是Currying
的典型例子
let me explain it by example 我以身作则
handleChange = field => event => {
this.setState({[field]:event.target.value})
}
Above function after Babel compilation becomes Babel编译后上述功能变为
const handleChange = function(field) {
return ( function(event) {
return 'something'
})
}
The second approach creates a closure
+ currying
type of function. 第二种方法创建函数的closure
+ currying
类型。 You can keep adding =>
and it will keep returning function. 您可以继续添加=>
,它将继续返回函数。 If you try to check the compiled code you could see something similar as above. 如果您尝试检查编译后的代码,则可能会看到类似上面的内容。
Hence In the first function 因此,在第一个功能
handleChange = (e, { value })
setState
works fine because the e
and {value}
are the function parameters and has no closure, however in second setState
可以正常工作,因为e
和{value}
是函数参数并且没有闭包,但是在第二个
handleChange = field => event =>
event
is the parameter of inner function in a closure. event
是闭包中内部函数的参数。 To read more about it you can go here Currying in JavaScript ES6 要了解更多有关它的信息,请转到此处。
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.