您有一个 GroceryApp 组件,它接收一个产品列表,每个产品都有名称和投票。应用程序应呈现一个无序列表,其中每个产品都有一个列表项。 产品可以被赞成或反对。 通过适当地使用 React state 和 props,实现赞成/反对逻辑。将状态保留在最顶层的组件中,而 Product 组件应该接受 props。
例如,将以下数组作为 products 属性传递给 GroceryApp [{ name: "Oranges", votes: 0}, { name: "Bananas", votes: 0 }] 并单击 Oranges 旁边的“t”按钮应该HTML 的结果如下:
‹div id="root"›
‹ul>
‹li›
‹ span›Oranges</span> - ‹span›votes: 1</span>
‹button >+‹/button> ‹button>-</button>
‹/li>
‹ li >
‹span>Bananas</span> - ‹span>votes: 0‹/ span>
‹button >+</button> ‹button>-</button>
‹/li>
</ul>
‹/div›
答案::
import React from 'react';
import { createRoot } from 'react-dom/client';
const Product = props => {
const plus = () => {
props.onVote('+', props.index)
};
const minus = () => {
props.onVote('-', props.index)
};
return (
<li>
<span>{props.prod.name}</span> - <span>votes: {props.prod.votes}</span>
<button onClick={plus}>+</button>{" "}
<button onClick={minus}>-</button>
</li>
);
};
const GroceryApp = (props) => {
let [products, setProducts] = React.useState(props.products);
const onVote = (dir, index) => {
let newProducts = [...products]
if(dir === '-'){
newProducts[index].votes--
}
else if(dir === '+'){
newProducts[index].votes++
}
setProducts(newProducts)
};
return (
<ul>
{
products.map((prod, i)=> <Product key={prod.name+"#"+i} prod={prod} index={i} onVote={onVote}/> )
}
</ul>
);
}
document.body.innerHTML = "<div id='root'></div>";
const root = createRoot(document.getElementById("root"));
root.render(<GroceryApp
products={[
{ name: "Oranges", votes: 0 },
{ name: "Bananas", votes: 0 }
]}
/>);
setTimeout(() => {
let plusButton = document.querySelector("ul > li > button");
if(plusButton) {
plusButton.click();
}
setTimeout(() => {
console.log(document.getElementById('root').outerHTML);
});
});