[英]How do I execute a function passed as props between components in React?
[英]How do I link React components to unique URLS based on input props?
我正在用 React 创建一个食谱网站,并尝试将每个食谱链接到一个独特的 URL。
我有一个包含食谱的数据库,其中一个根据单击的按钮呈现为<Recipe/>
组件(这些按钮也会自动生成)。
import Recipe from './recipe.js'
import Recipes from '../data/recipes.js'
export default function Main(){
const [currentRecipe, setCurrentRecipe] = React.useState(<div></div>)
//Below generates all buttons for all recipes available, with corresponding parameter for function call
const allButtons = Recipes.map(recipe => {
return(
<button className="recipeButton" onClick={()=>RenderRecipe(recipe.Name)}>{recipe.Name}</button>
)
})
//Below function then generates a recipe based on which button was clicked
function RenderRecipe(recipeName){
Recipes.map(recipe => {
if (recipe.Name===recipeName){
const newRecipe =
<Recipe
name={recipe.Name}
ingredients={recipe.Ingredients}
instructions={recipe.Instructions}
numberOfPeople={8}
/>
setCurrentRecipe(newRecipe)
}
})
}
return (
<div>
{allButtons}
{currentRecipe}
</div>
)
}
食谱显示工作正常,但一切都发生在同一个 URL 上,我希望用户能够在他们的浏览器中为食谱添加书签,并且 go 在食谱之间来回切换。 有没有办法执行以下操作:
'pancakesbutton'.onclick("渲染煎饼<Recipe/>
并将 URL 更改为 index.html/pancakes)"
(最好以网站知道 index.html/pancakes 应该显示煎饼食谱的方式)
我研究了 react-router-dom,但似乎它需要您为每个配方制作单独的文件。 有没有办法避免这种情况?
提前致谢!
您可以将实际配方显示移动到不同的组件,并且可以定义该组件的所有配方路径。 所以基于 URL 路径可以编写显示对应菜谱的逻辑。
<Route exact path={["/pancakes", "/another-recipe"]}>
<RecipeComponent />
</Route>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.