【问题标题】:Pass props from child component to parent on select option change在选择选项更改时将道具从子组件传递给父组件
【发布时间】:2018-07-12 22:54:36
【问题描述】:

我有一个选择下拉组件作为子组件,其中选项(类别列表)由 API 在父组件中的 componentDidMount 上生成。当用户选择选项(类别)时,必须将所选值传递回父组件。父组件根据所选值执行获取请求,并将结果作为选项(产品列表)传递给另一个具有一个选择下拉菜单。

我想将这些子组件保留为无状态函数,因为它可以在多个组件中使用。

所以,类别列表在选择下拉列表中作为道具传递----开发者工具:

但不在网页上。

父容器

 categories() {
    return this.props.category && this.props.category.map((category) =>
    <option key={category.id} value={category.name} className="textTransform">
    {category.name.charAt(0).toUpperCase() + category.name.slice(1)}
    </option>
  )
}

onChangeOption(e){
  if (e.detail === 0){
    // console.log(e.target.value);
    this.props.productLoad(e.target.value);
  }
}

在父组件的渲染函数中

<SelectCategory
  changeOption={this.onChangeOption}
  fetchCategory={this.categories()}
/>

子组件(SelectCategory)

import React from 'react'
import { Field,reduxForm } from 'redux-form';

const SelectCategory = (changeOption,fetchCategory) => (
  <div className="col-sm-3 col-md-3 col-lg-3 ">
    <div className="form-group">
        <Field
        name="selectCategory"
        component="select"
        className="form-control"
        onClick={changeOption()}
        >
        <option value="0" disabled>Select Category</option>
        { fetchCategory() }
      </Field>
    </div>
  </div>
)

export default SelectCategory

【问题讨论】:

  • 它必须是 changeOption() 而不是 this.changeOption() 在您的孩子中,您是从传递的道具中获得的。它不是绑定在你的 this 上的函数。
  • 是的,是的。但是它显示了一个错误 Uncaught TypeError: changeOption is not a function,因为数据不存在于 DOM 中。现在,我已经更新了我的代码。

标签: javascript reactjs redux ecmascript-6 dom-events


【解决方案1】:

我通过在父函数中使用回调来实现它

myCallback = (selectedCategory) => {
    this.props.productLoad(selectedCategory);
}

并且回调作为props传递给子组件

<SelectCategory
 Categories={this.props.category}
 callbackFromParent={this.myCallback}
/>

因此,在子组件中,在事件触发时,我调用了函数onchangeOption,该函数又将选定的值传递给父组件中存在的回调。

onChangeOption=(e)=>{
    if (e.detail === 0){
      this.props.callbackFromParent(e.target.value);
    }
  }

【讨论】:

    【解决方案2】:

    子组件不会更新,因为您没有更新它的任何道具:

    • 仍然通过相同的选项
    • 仍然传递相同的 onChange 函数

    您应该在子组件中创建一个额外的道具,称为“selectedOption”并从父组件传递它。因此,这个 prop 会改变,子组件也会更新。

    希望这会有所帮助。 如果我误解了这个问题,我们深表歉意!

    【讨论】:

    • 谢谢拉杜,修改方法和内容,请说清楚。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 2016-06-10
    • 1970-01-01
    • 2020-11-23
    • 2021-01-16
    相关资源
    最近更新 更多