我正在尝试在用户点击点击区域时传递帐户的所选ID。
<Link to="/account" id={1234}>
但是,在我的帐户组件中,这个“要”将我们带到:
<Route path="/account" component={Account}/>
我得到了未定义。
export default class Account extends Component {
constructor(props) {
super(props);
alert(props.id);
有没有办法使用链接将道具传递给我的组件?
答案 0 :(得分:1)
我认为最好的方法是将您的帐户ID定义为路线中的参数,例如
<Route path="/account/:id" component={Account}/>
<Link to='/accounts/123'> Go to Accounts</Link>
并使用props.match.params.id
访问它,但如果您想通过道具发送,请执行以下操作:
<Link to={{ pathname: '/account', state: { id: '123'} }}>Go to Accounts</Link>
并在帐户中:
const { id } = props.location.state
答案 1 :(得分:0)
要将道具传递给儿童,你可以这样做
<Route
path="/new/path"
render={(routeProps) => (
<MyComponent {...routeProps} {...props} />
)}
/>
并且不要跳过传播运营商。
答案 2 :(得分:0)
将信息传递给路径的链接的简洁方法是使用URL中的参数:
// 1. Link to what would be the URL for a specific account.
// would probably replace `1234` for a variable here
<Link to={`/account/${1234}`>View Account 1234</Link>
// 2. "capture" the ID in the url using a param matcher
// We'll receive this param as "props.match.params.id" in the render function
// using component={} also works here, and the props will be injected directly into the component instead,
// but render={} here looks cleaner to me, and is more flexible if you wanna pass more props
<Route path="/account/:id" render={props => <Account id={props.match.params.id} />} />
See the docs for more information on how the render
prop works.