我正在尝试将数据从DropDownItem
组件传输回我的类组件,而我无法使用props来完成。
在此示例中,我想将props.product
的点击项转移到我的应用程序组件中。
谁能告诉我最好的方法是什么?
预先感谢。
当我单击下拉选项时,我想将其显示为我的实例 主类组件。 我已经尝试为此目的创建一个特殊的组件,但这会使代码变得非常复杂。
class App extends Component {
constructor(props) {
super(props)
this.state = {
products: []
}
}
async fetchDevices() {
const url = 'my url';
const response = await fetch(url, { method: 'GET', headers: headers });
const data = await response.json()
this.setState({ products: data.value })
}
componentDidMount() {
this.fetchDevices();
}
render() {
const productItems = this.state.products.map((productValue, index) => {
return (<DropDownItem key={index} product={productValue.name} />)
})
return (
<div>
{this.state.products[0] && Array.isArray(this.state.products) ?
<div>
<DropdownComponent
isOpen={this.state.dropdownOpen}
toggle={this.toggle}
product={productItems}
/>
</div> :
<div>loading...</div>}
<p></p>
</div>
)
}
}
export default App
function DropDownItem(props) {
return (
<div>
<DropdownItem onClick={() => console.log("selected product", props.product)}>
{props.product}</DropdownItem>
<DropdownItem divider />
</div>
)
}
export default DropDownItem
我想在我的App组件中显示所选项目
答案 0 :(得分:0)
组件之间数据传输的一般规则是:
App
到子项(DropDownItem
)转移,请使用props
示例(未经测试,仅用于展示想法)
// App component
...
selectDropDownItem(item) {
this.setState({selectedItem: item});
}
render () {
return
// ...
<DropdownComponent
isOpen={this.state.dropdownOpen}
toggle={this.toggle}
product={productItems}
selectItemCallback={this.selectDropDownItem.bind(this)}/>
//...
// DropDownItem component
function DropDownItem (props) {
return (
<div>
// bind to props.product so when called props.product will be passed as argument
<DropdownItem onClick={props.selectItemCallback.bind (null, props.product)}>
{props.product}</DropdownItem>
<DropdownItem divider/>
</div>
)
}
export default DropDownItem
一般的想法是您将回调从父级传递给子级。当孩子需要与父母沟通时,它只调用在props中传递的回调,并将所需数据作为该回调的参数传递(在您的示例中,可以选择此项)