gpt4 book ai didi

javascript - 如何从Reactjs中的子组件获取多个值?

转载 作者:行者123 更新时间:2023-12-02 22:27:58 26 4
gpt4 key购买 nike

我想在父组件的单个方法中获取两个值。将 props 值从子组件传递到父组件。什么是合适的解决方案?

  1. Form.js(子组件)
 // 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>
  • App.js(父组件)
  • 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/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com