繁体   English   中英

将onClick按钮分配给适当的功能。 地图功能ReactJS

[英]Assigning onClick button to the proper feature. Map function ReactJS

我创建了这个模型,并试图将其放入现实生活中的组件模型

我从简单的事情开始,所以我创建了3个按钮和一个数组,但是发生的是,当我单击任意按钮时,我看到了所有功能,而我的目标是当我单击SMS时看到了sms.features等。现在我看到这样的结果

import React, { Component } from "react";

export default class Test extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isHidden: true,
      features: [
        {
          name: "sms.features",
          key: "1",
          icon: "sms icon"
        },
        {
          name: "pricing.features",
          key: "2",
          icon: "pricing icon"
        },
        {
          name: "api.features",
          key: "3",
          icon: "api icon"
        }
      ],
      buttons: [
        {
          name: "sms",
          key: 1
        },
        {
          name: "pricing",
          key: 2
        },
        {
          name: "api",
          key: 3
        }
      ]
    };
    this.toggleHidden = this.toggleHidden.bind(this);
  }

  toggleHidden() {
    this.setState({
      isHidden: !this.state.isHidden
    });
  }

  render() {
    return (
      <div style={{ marginLeft: "20%" }}>
        <div className="features__details__grid">
          {!this.state.isHidden &&
            this.state.features.map((object, key) => (
              <div key={key}>{object.name}</div>
            ))}
        </div>
        <div className="buttons">
          {this.state.buttons.map((button, key) => (
            <div key={key}>
              <button onClick={this.toggleHidden}>{button.name}</button>
            </div>
          ))}
        </div>
      </div>
    );
  }
}

因此,由于您只想显示一个,因此isHidden应该是一个指向应该可见的功能的指针( 通过指定key属性

 import React, { Component } from "react"; export default class Test extends Component { constructor(props) { super(props); this.state = { visibleFeature: "0", features: [ { name: "sms.features", key: "1", icon: "sms icon" }, { name: "pricing.features", key: "2", icon: "pricing icon" }, { name: "api.features", key: "3", icon: "api icon" } ], buttons: [ { name: "sms", key: "1" }, { name: "pricing", key: "2" }, { name: "api", key: "3" } ] }; this.toggleHidden = this.toggleHidden.bind(this); } toggleHidden(key) { this.setState(state=>{ if (state.visibleFeature === key) return {visibleFeature: 0} return {visibleFeature: key} }); } render() { const feature = this.state.visibleFeature; return ( <div style={{ marginLeft: "20%" }}> <div className="features__details__grid"> {this.state.features.map((object) => ( feature === object.key && <div key={object.key}>{object.name}</div> ))} </div> <div className="buttons"> {this.state.buttons.map((button) => ( <div key={button.key}> <button onClick={()=>this.toggleHidden(button.key)}>{button.name}</button> </div> ))} </div> </div> ); } } 

演示在https://codesandbox.io/s/8y5q120wxj

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM