如何使用 NavLink 将道具传递给组件
How to pass props to component with NavLink
我正在尝试使用 NavLink 将道具发送到组件。
<NavLink to={{pathname :"/wind", state:{from: "This is my props"}}} >Wind</NavLink>
我想在这个组件中获取它,
import React from 'react';
import { useLocation} from "react-router-dom"
const Wind = () =>{
const location = useLocation();
const {from} = location.state;
console.log({from})
return (
<div className="Wind">
<h1>Wind</h1>
</div>
);
}
export default Wind;
不幸的是,这给了我结果
所以我这样试试
import React from 'react';
const Wind = (props) =>{
//console.log(props.location.state)
return (
<div className="Wind">
<h1>Wind</h1>
</div>
);
}
export default Wind;
这种情况下的控制台日志未定义。
我不知道为什么它没有任何想法?
在新版本中,state 作为一个单独的 prop 传递。尝试使用
<NavLink to={{pathname :"/wind"}}
state={{from: "This is my props"}} >Wind</NavLink>
然后组件尝试像这样获取
import React from "react";
import { useLocation } from "react-router-dom";
const Wind = () => {
const location = useLocation();
const { state } = location;
console.log(state.from);
return (
<div className="Wind">
<h1>Wind</h1>
</div>
);
};
export default Wind;
我正在尝试使用 NavLink 将道具发送到组件。
<NavLink to={{pathname :"/wind", state:{from: "This is my props"}}} >Wind</NavLink>
我想在这个组件中获取它,
import React from 'react';
import { useLocation} from "react-router-dom"
const Wind = () =>{
const location = useLocation();
const {from} = location.state;
console.log({from})
return (
<div className="Wind">
<h1>Wind</h1>
</div>
);
}
export default Wind;
不幸的是,这给了我结果
所以我这样试试
import React from 'react';
const Wind = (props) =>{
//console.log(props.location.state)
return (
<div className="Wind">
<h1>Wind</h1>
</div>
);
}
export default Wind;
这种情况下的控制台日志未定义。 我不知道为什么它没有任何想法?
在新版本中,state 作为一个单独的 prop 传递。尝试使用
<NavLink to={{pathname :"/wind"}}
state={{from: "This is my props"}} >Wind</NavLink>
然后组件尝试像这样获取
import React from "react";
import { useLocation } from "react-router-dom";
const Wind = () => {
const location = useLocation();
const { state } = location;
console.log(state.from);
return (
<div className="Wind">
<h1>Wind</h1>
</div>
);
};
export default Wind;