我有:
<DropdownMenu text="Sort by" isOpen={this.state.activeDropdown === "Sort_by"} onSelect={this.setSort.bind(this)}
onClick={this.showDropdown.bind(this, "Sort_by")}
onMouseEnter={() => this.setState({mouseInDropdown: true})}
onMouseLeave={() => this.setState({mouseInDropdown: false})}>
<div onMouseEnter={() => this.setState({mouseInDropdown: true})}
onMouseLeave={() => this.setState({mouseInDropdown: false})}>
<li>Name</li>
<li>Age</li>
<li>Value</li>
</div>
</DropdownMenu>
您可以看到其中包含:
<li>Name</li>
<li>Age</li>
<li>Value</li>
在DropdownMenu.js中,我有:
render() {
return <div className="dropdown__menu" onClick={this.props.onClick}>
{this.props.text} {this.state.count > 0 ? <b>{this.state.count}</b> : ''}
<div className="dropdown__content"
style={this.props.isOpen ? {'display': 'block'} : {'display': 'none'}}>
{
this.props.children
}
</div>
</div>
}
this.props.children
呈现了这些选项,但是如何将this.props.onSelect
绑定到每个选项,以获取所选子项的值?
答案 0 :(得分:0)
render() {
return <div className="dropdown__menu" onClick={this.props.onClick}>
{this.props.text} {this.state.count > 0 ? <b>{this.state.count}</b> : ''}
<div className="dropdown__content"
style={this.props.isOpen ? {'display': 'block'} : {'display': 'none'}}>
{
React.Children.map(this.props.children, child => React.cloneElement(child, { onSelect: this.props.onSelect})
);
}
</div>
</div>
}
为了将列表项的值传递给onSelect回调,我建议创建一个功能组件
const ListItem = ({ onSelect, value }) => (
<li onClick={() => onSelect(value)}>{value}</li>
)
然后您将<ListItem value={"name"}>
等替换为li。
答案 1 :(得分:0)
另一种解决方案是将onSelect事件直接传递到列表项。
<DropdownMenu text="Sort by" isOpen={this.state.activeDropdown === "Sort_by"}
onClick={this.showDropdown.bind(this, "Sort_by")}
onMouseEnter={() => this.setState({mouseInDropdown: true})}
onMouseLeave={() => this.setState({mouseInDropdown: false})}>
<div onMouseEnter={() => this.setState({mouseInDropdown: true})}
onMouseLeave={() => this.setState({mouseInDropdown: false})}>
<li onClick={(() => onSelect("name")}>Name</li>
<li onClick={(() => onSelect("age")}>Age</li>
<li onClick={(() => onSelect("value")}>Value</li>
</div>
</DropdownMenu>