![](/img/trans.png)
[英]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.