我想在父组件的单一方法中获得两个值。将props值从Child传递到Parent Component。什么是合适的解决方案?
// First method -> Here I get the value in suggestion which is then
// passed to Parent Component via props
onSuggestionSelected = (event, {suggestion}) => {
this.props.getWeather(suggestion)
}
// Second method -> Here is the value which I want to pass via
// props
onClick = (e) => {
e.preventDefault()
const value = e.target.value
this.props.getWeather(value)
}
// Autosuggest Input Component
// Here I get suggestion value
<Autosuggest
onSuggestionSelected={this.onSuggestionSelected}
/>
// Button Component
// Here I pass the input value to onClick method
<MDBBtn
type="submit"
value={inputProps.value}
onClick={e => this.onClick(e)}
>
Search Weather
</MDBBtn>
getWeather = async (suggestion, value) => {
// Here I get suggestion values
const city = suggestion.name;
const country = suggestion.country;
// Here I get undefined
console.log('VALUE', value)
}
因此,按照上面的代码,如何从子组件中获取两个值?可能吗?任何建议或变更
有多种处理方法,但是您不能添加两个参数并使用一个参数调用该函数。
如果建议和值的行为方式不同,一种方法可以添加标志
onSuggestionSelected = (event, {suggestion}) => {
const isSuggestion = true
this.props.getWeather(suggestion, isSuggestion)
}
onClick = (e) => {
e.preventDefault()
const value = e.target.value
const isSuggestion = false
this.props.getWeather(value, isSuggestion)
}
最后很少对App.js进行重构(父组件)
getWeather = (suggestionOrValue, isSuggestion) => {
if(isSuggestion){
//use suggestionOrValue as suggestion
}
else {
//use suggestionOrValue as value
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句