【问题标题】:How to pass an object with onClick React?如何使用 onClick React 传递对象?
【发布时间】:2019-06-14 12:06:21
【问题描述】:

我在外部文件中有一个对象,我想将 url 传递到按钮 onClick 但我不知道传递值。

对象:

const ProjectLists = [

    {
        id: "4",
        iconImage: "",
        name: "Simple",
        description: "Simple is a corporate responsive template and the absolutely clean & modern template theme for your business. The theme was built by Foundation Framework and take advantages of it features: grid system, typography, buttons, form, UI element, section and more.",
        technologies: "HTML, CSS, JavaScript",
        href: "http://striped-dolls.surge.sh"
    }
]

export default ProjectLists;

如何将map() 中的ProjectLists.map((project, i) => href 传递给<button>

class Projects extends Component {
  render() {
    return (
      <div>
        {ProjectLists.map((project, i) =>

        <section className='section'>
          <div className='row'>
            <div className='col-sm'>
              <div className='content-left'>
                <p key={project.id + i}>
                  {project.iconImage}
                </p>
              </div>
            </div>
            <div className='col-sm-8'>
              <div className='content-right text-left'>
                <h1>{project.name}</h1>
                <p>{project.description}</p>
                <p>Technologies: {project.technologies}</p>
                <button type='submit' onClick=() => </button>>View live</button>
              </div>
            </div>
          </div>
        </section>
        )}
      </div>
    )
  }
}

感谢您的帮助!

【问题讨论】:

标签: arrays reactjs object


【解决方案1】:

您可以使用箭头函数在地图中传递额外数据:

{ProjectLists.map(project =>
  <button onClick={onProjectClick(project)}>View live</button>
}

// e.g.
onProjectClick = project => event => {
  console.log(project.description);
  navigateTo(project.href);
}

我注意到你的按钮有type="submit",所以更正确的处理事件是表单元素上的onSubmit,但是因为它处理按下回车键的例子(虽然它不是必需的)。

【讨论】:

  • 谢谢,但我想通过&lt;Button&gt;onClick 传递它。
  • 不知道你的意思,我只是向你展示了如何将项目数据传递到按钮的onClick事件中??
  • 我是 React 的初学者。如果我不明白这一切,我很抱歉。在哪里可以将此功能添加到class Projects? ``` onProjectClick = 项目 => 事件 => { console.log(project.description);导航到(项目.href); } ```
  • 我在render() 之前添加了onProjectClick,但它一直显示错误!
  • 您应该将它添加到与 render() 相同的级别(之前或之后不重要),但也许您没有在项目中使用 @babel/plugin-proposal-class-properties,因为那样您会收到错误.我强烈推荐使用它,因为它可以让 React 中的事件回调工作更加清晰
【解决方案2】:

您可以为此使用“a”标签。

<a href={project.href}></a>

如果你想在你的按钮中使用 onClick,那么你可以试试这个。

onClick={() => { window.location.href = project.href }}

【讨论】:

  • 此解决方案有效,但我想知道如何在 onClick() 中传递 {project.href}。可以举个例子吗?
【解决方案3】:
  state = {
    redirect: false
  }
  setRedirect = (href) => {
    window.location.href = href;
  }

调用setRedirect函数

<button onClick={()=>this.setRedirect(project.href)}>View live</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-21
    • 2017-12-22
    • 2017-04-25
    • 1970-01-01
    • 2019-06-02
    • 2018-08-01
    • 2021-05-08
    • 2014-02-16
    相关资源
    最近更新 更多