如何在React中传递道具onClick

时间:2016-12-09 21:10:00

标签: reactjs react-router

我有使用axios.get调用的事件列表,并将它们映射到Event组件。在Event组件内部,我有一个打开注册组件的按钮。我正试图找到一种方法在React Router Link组件上传递this.props.title。

Events.js

import React from 'react';
import Event from './Event';
var axios = require('axios');

var Events = React.createClass({
     getInitialState: function() {
    return {
        events: [], 
    }
  },
  componentDidMount: function() {
    var _this = this;
      axios.get("MY JSON URL")
        .then(function(result) {
          _this.setState({
            events: result.data
          });
        })
        .catch(function(error) {
            console.log(error);
        })
  },
    componentWillUnmount: function() {
        this.unmounted = true;
  },
    render: function() {
        return (
            <div>
                {this.state.events.map(function(event, key) {
                    return (
                        <div key={key}>
                            <Event 
                                title={event.EventTitle}
                              />
                        </div>
                    ) 
                })}
            </div>
        )
    }
});

export default Events;

Event.js     从'react'中导入React;

var Event = React.createClass({
render: function() {
return (
  <div className="ui-outer">
    <Link to="/register/event" title={this.props.title} />
  </div>
)}})
export default Event;

RegisterForm.js

import React from 'react';
var RegisterForm = React.createClass({
 <h1>{this.props.title}</h1>
 <form></form>
})
export default RegisterForm;

1 个答案:

答案 0 :(得分:4)

您可以通过<Link>两种方式传递信息:通过URI或状态。

通过URI,您可以在pathname(使用param)或search字符串(或query对象)中包含信息。< / p>

// props.title through the pathname
<Link to={{
  pathname: `/register/event/${this.props.title}`
}}>{this.props.title}</Link>

在您的组件中,您可以通过this.props.location.pathname访问此内容。

// props.title through the search
<Link to={{
  pathname: '/register/event',
  search: `?title=${this.props.title}`
}}>{this.props.title}</Link>
// props.title through the query
<Link to={{
  pathname: '/register/event',
  query: { title: this.props.title }
}}>{this.props.title}</Link>

在您的组件中,您可以通过this.props.location.query.title访问这两个。

在URI中添加标题的好处是,您可以为某人提供指向该页面的直接链接,并且他们将包含title

您可以通过<Link>传递信息的另一种方法是使用位置的state属性。这允许您通过<Link>传递“隐藏”信息。这样做的缺点是,直接导航到URL的人无法获得额外的信息。

// props.title through the state
<Link to={{
  pathname: '/register/event',
  state: { title: this.props.title }
}}>{this.props.title}</Link>
相关问题