【问题标题】:Render Component Only Once in a Div Below an LI When In-Line Button is Clicked单击内联按钮时,仅在 LI 下方的 Div 中渲染组件一次
【发布时间】:2018-01-14 03:10:51
【问题描述】:

目前,当单击 img 时,这将在每个列表项下方呈现一个组件,方法是将每个索引显示的组件数组保持在本地状态。例如。 (state.showItems ==[true,false,false,true])。

我想将此数组中的值一次限制为一个“真”,以便<SuggestStep /> 组件在单击按钮下的 div 中仅呈现一次。我没有使用 CSS,因为列表可能会变得非常大,并且不想为每个列表呈现和隐藏​​一个组件。也考虑使用显示为图像的单选按钮,但不知道这是否会涉及将表单与 LI 混合以及这是否不好。欢迎对将 showItems 数组项一次限制为一个 true 的问题提供反馈,并欢迎解决我所描述的组件渲染问题的一般模式。

class CurrentSteps extends Component {
      constructor(props) {
        super(props)
        this.state = {
          toggleOnSuggestInput: false,
          showItems: []
    }
      this.clickHandler = this.clickHandler.bind(this)
    }

    clickHandler(index){
      let showItems = this.state.showItems.slice();
      showItems[index] = !showItems[index]
      this.setState({showItems})
      this.setState(prevState => ({
        toggleOnSuggestInput: !prevState.toggleOnSuggestInput
      }))
    }

      render() {

      let steps = this.props.currentGoalSteps.map((step, index) => {
          return (
            <div key={`divKey${index}`}>
              <li key={index}>{step}</li>
              <img  key={`imageKey${index}`} onClick={this.clickHandler.bind(this,index)} alt="" src={plus}/>
              {this.state.showItems[index] ? <SuggestStep /> : null}
            </div>
                )
            });

    return (
             <div>
            <ul> {steps} </ul>
             </div>
    )
    }

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    尝试对您的代码进行以下修改...

    像这样更改您的this.state

    this.state = {
        toggleOnSuggestInput: false,
        activeIndex: null
    };
    

    将您的 clickHandler 更改为此。

    clickHandler(event, index) {
        this.setState({ activeIndex: index })
    }
    

    将您的map 更改为喜欢下面的那个。注意 onClick 属性更改。

    let steps = this.props.currentGoalSteps.map((step, index) => {
        return (
            <div key={`divKey${index}`}>
                <li key={index}>
                    {step}
                </li>
                <img
                    key={`imageKey${index}`}
                    onClick={e => this.clickHandler(e, index)}
                    alt=""
                    src={plus}
                />
                {this.state.activeIndex === index ? <SuggestStep /> : null}
            </div>
        );
    });
    

    【讨论】:

    • 果然这似乎与文本工作得很好,尽管在初始点击后出于某种原因,我的组件 无法在随后的点击中静默加载。
    • 静默是什么意思?
    • 我的意思是在 的渲染挂起时,我在控制台中没有看到任何错误
    • 这就是我的意思,没有错误。在第二次点击时,我只看到我的“正在加载...”占位符 应该是
    • 但是用

      Bob

      替换 工作正常。因此,为什么我对答案总体感到满意...
    猜你喜欢
    • 2021-11-08
    • 2020-11-24
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多