【问题标题】:passing props in React with a map function使用 map 函数在 React 中传递道具
【发布时间】:2020-09-30 10:58:28
【问题描述】:

我知道如何在 React 中传递基本的道具,但我对这个有点难过。我认为展示会更好地解决问题,而不是试图在本段中解释所有内容。

这是试图将其分解为自己的独立组件之前的情况。

    { <div className="flex-item-main">
         <ol>
            {this.state.thoughts.map((thought, index)=> 
                <DisplayPoem className='displayPoem' key={index} onClick={() => { this.handleDeleteClick(index) }} name='Delete Thoughts' value={thought} />
            )}
          </ol>
         </div> }

这是它自己的独立组件从父组件获取道具的外观:

    { <div className="flex-item-main">
         <ol>
            {this.props.thoughtsProp.map((thought, index)=> 
                <DisplayPoem className='displayPoem' key={index} onClick={this.props.onClick} name={this.props.name} value={thought} />
            )}
          </ol>
         </div> }

这是传递 props 的父组件:我不知道如何处理 onClick={() =&gt; { this.handleDeleteClick(index) }},因为我需要组件中 .map() 函数中的 index。我希望这一切都有意义,我很乐意添加更新,我不知道如何解释这个问题,这可能是我无法解决它的原因。 React 还是新手。

         <DisplayPoemList thoughtsProp={this.state.thoughts}  onClick={() => { this.handleDeleteClick(index) }} name='Delete Thoughts' />

【问题讨论】:

    标签: javascript reactjs function components state


    【解决方案1】:

    您可以从道具中删除箭头功能并将方法作为道具传递给您。 更改此代码(查看onClick):

    <DisplayPoemList thoughtsProp={this.state.thoughts}  onClick={() => { this.handleDeleteClick(index) }} name='Delete Thoughts' />
    

    到此代码:

    <DisplayPoemList thoughtsProp={this.state.thoughts}  onClick={this.handleDeleteClick } name='Delete Thoughts' />
    

    然后你的DisplayPoemList 将得到一个函数onClick,它在调用时期待index。 使用箭头函数创建函数的实例,并在每个元素的范围内创建索引。

        { <div className="flex-item-main">
             <ol>
                {this.props.thoughtsProp.map((thought, index)=> 
                    <DisplayPoem className='displayPoem' key={index} onClick={() => this.props.onClick(index)} name={this.props.name} value={thought} />
                )}
              </ol>
             </div> }
    

    【讨论】:

      猜你喜欢
      • 2020-12-19
      • 1970-01-01
      • 1970-01-01
      • 2019-07-06
      • 2017-03-06
      • 2018-04-27
      • 1970-01-01
      • 2021-04-01
      • 1970-01-01
      相关资源
      最近更新 更多