gpt4 book ai didi

javascript - 如何将 props 传递给从组件数组映射的组件?

转载 作者:行者123 更新时间:2023-11-28 04:03:33 25 4
gpt4 key购买 nike

我是 React 新手,有时对术语感到困惑。我的问题是,我正在创建一个 ScrollableList 组件,这些组件作为数组 Prop 传递给 ScrollableList。然后,ScrollableList 将每个组件映射到 div 内,这不允许我将 props 传递给组件,例如“handleChange”。还有另一种我不知道的方法可以做到这一点吗?

ScrollableList渲染:

render() {
const startPosition = this.state.scrollPosition -
this.props.maxItemsToRender > 0
? this.state.scrollPosition - this.props.maxItemsToRender
: 0

const endPosition = this.state.scrollPosition +
this.props.maxItemsToRender >=
this.props.listItems.length
? this.props.listItems.length
: this.state.scrollPosition + this.props.maxItemsToRender

return (
<div className="react-scrollable-list" ref="list" style={this.props.style}>
<div
key="list-spacer-top"
style={{
height: startPosition * this.props.heightOfItem
}}
/>
//Where My Problem Begins
{this.props.listItems.slice(startPosition, endPosition).map(item => (
<div handleChange={this.handleChange}
className="react-scrollable-list-item"
key={'list-item-' + item.id}>
{item.content}
</div>
))}
<div
key="list-spacer-bottom"
style={{
height: this.props.listItems.length * this.props.heightOfItem -
endPosition * this.props.heightOfItem
}}
/>
</div>
)
}

{item.content} 包含我希望将 prop handleChange={this.handleChange} 传递给的组件。有办法做到这一点还是我的设计有问题?

最佳答案

您可以将项目提取到单独的函数

renderItem(item) {
const Content = item.content;

return (
<div
handleChange={this.handleChange}
className="react-scrollable-list-item"
key={item.id}
>
<Content foo="bar" someProp={9} />
</div>
);
}

render() {
const startPosition = this.state.scrollPosition -
this.props.maxItemsToRender > 0
? this.state.scrollPosition - this.props.maxItemsToRender
: 0

const endPosition = this.state.scrollPosition +
this.props.maxItemsToRender >=
this.props.listItems.length
? this.props.listItems.length
: this.state.scrollPosition + this.props.maxItemsToRender

return (
<div className="react-scrollable-list" ref="list" style={this.props.style}>
<div
key="list-spacer-top"
style={{
height: startPosition * this.props.heightOfItem
}}
/>
//Where My Problem Begins
{this.props.listItems.slice(startPosition, endPosition).map(item => this.renderItem(item))}
<div
key="list-spacer-bottom"
style={{
height: this.props.listItems.length * this.props.heightOfItem -
endPosition * this.props.heightOfItem
}}
/>
</div>
)
}

关于javascript - 如何将 props 传递给从组件数组映射的组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46886795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com