首页 文章

在选择选项更改时将子组件中的道具传递给父组件

提问于
浏览
0

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

我想将这些子组件保持为无状态功能,因为它可以在多个组件中使用 .

因此,类别列表在选择下拉列表中作为道具传递----开发人员工具
img
但不在网页上 .

父容器

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);
  }
}

在父组件的render函数中

<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

2 回答

  • 0

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

    • 仍然传递相同的选项

    • 仍然传递相同的onChange函数

    您应该在子组件中创建一个名为“selectedOption”的附加prop,并从父组件传递它 . 因此,此prop将更改并且子组件将更新 .

    希望这可以帮助 . 如果我误解了这个问题,请道歉!

  • 0

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

    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);
        }
      }
    

相关问题