我正在处理一组数组,这些数组通过 API 调用作为按钮打印到屏幕上。
我想添加我的基础/糖霜按钮(选择一个),然后将每个选定按钮的键添加到新的 OrdersArray。我还需要能够选择多个浇头(多选)并将它们添加到 OrdersArray 中的嵌套数组。
我还想在每个选定按钮被选中时更改它们的颜色。
My Buttons 函数生成按钮。
function Buttons({ list }) {
const style = {
display: 'inline-block',
textAlign: 'center',
border: '1px solid black',
padding: '10px',
margin: '10px',
width: '35%'
}
return (
<div>
{list && list.map(item =>
<button key={item.key}
style={style}
>
{/* <p>{item.key}</p> */}
<p>{item.name}</p>
<p>${item.price}.00</p>
{/* <p>{item.ingredients}</p> */}
</button>
)}
</div>
);
};
我的应用程序组件呈现按钮。
Class App extends Component {
constructor() {
super();
this.state = {
'basesObject': {},
'frostingsObject': {},
'toppingsObject': {},
selectedButton: null
}
}
componentDidMount() {
this.getBases();
this.getFrostings();
this.getToppings();
}
/* GET DATA FROM SERVER */
getBases() {
fetch('http://localhost:4000/cupcakes/bases')
.then(results => results.json())
.then(results => this.setState({'basesObject': results}))
}
getFrostings() {
fetch('http://localhost:4000/cupcakes/frostings')
.then(results => results.json())
.then(results => this.setState({'frostingsObject': results}))
}
getToppings() {
fetch('http://localhost:4000/cupcakes/toppings')
.then(results => results.json())
.then(results => this.setState({'toppingsObject': results}))
}
render() {
let {basesObject, frostingsObject, toppingsObject} = this.state;
let {bases} = basesObject;
let {frostings} = frostingsObject;
let {toppings} = toppingsObject;
return (
<div>
<h1>Choose a base</h1>
<Buttons on
list={bases}
/>
<h1>Choose a frosting</h1>
<Buttons
list={frostings}
/>
<h1>Choose toppings</h1>
<Buttons
list={toppings}
/>
</div>
);
}
}
我是 React 新手,如有任何帮助,我们将不胜感激! :)
最佳答案
您需要将一个函数传递给按钮,该函数将在单击按钮时修改父组件中的状态值。
在 parent 中:
const addToOrder = item => {
orderArray.push(item);
const newOrder = orderArray.reduce((acc, order) => {
return acc + " " + order.name;
}, "");
setOrder(newOrder);
};
...
<Button addToOrder={addToOrder} />
在 Button.js 中
<button onClick={() => addToOrder(item)} >
Check out the whole thing in this Sandbox
要跟踪哪些按钮已被单击,您需要在按钮组件本身或父容器中跟踪按钮状态(如果您想让按钮保持无状态)。然后根据该状态将按钮属性 disabled 设置为 true 或 false。
<button disabled={isButtonDisabled} />
抱歉,我没有时间充实完整的内容,但这应该能让您朝着正确的方向前进。
关于javascript - 处理按钮选择+将所选项目添加到新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59620210/