作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想在父组件的单个方法中获取两个值。将 props 值从子组件传递到父组件。什么是合适的解决方案?
// 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
}
}
关于javascript - 如何从Reactjs中的子组件获取多个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58995846/
我是一名优秀的程序员,十分优秀!