【发布时间】: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