我有两个类别“ A”和“ B”。在单击时,类别“ A”的任何按钮将删除按钮,并且必须移至类别“ B”;在单击时,类别“ B”的任何按钮都将按钮添加到类别“ A”,并且必须从类别“ B”移动。
export const LauncherButtons = [
{
linked: false,
type: 'ABC',
name: 'ReactJs'
},
{
linked: false,
type: 'ABC',
name: 'VueJS'
},
{
linked: true,
type: 'XYZ',
name: 'Angular'
},
{
linked: true,
type: 'XYZ',
name: 'Javascript'
}
];
这是我为类别“ A”渲染的内容。
{ LauncherButtons.map((button,index) => {
return(
button.linked === true &&
<LauncherActionButton
text={button.name}
onClick = {this.removeAction}/>
);
})}
渲染类别“ B”。
{ LauncherButtons.map((button,index) => {
return(
button.linked !== true &&
<LauncherActionButtonAdd
textAdd={button.name}
onClick = {this.addAction}/>
);
})}
因此,基本上,当我单击类别“ A”(真)的按钮时,它应该移至类别“ B”并变为假,类似地,当我单击类别“ B”的按钮(假)时,应该变为真实并移至类别“ A”。
答案 0 :(得分:1)
尝试类似这样的操作:https://codesandbox.io/s/holy-leftpad-hw1oe
我已经布置了两个部分,一个活动部分和一个非活动部分。通过单击按钮,将其移至另一侧。我不知道您的LauncherActionButton
组件是什么样子,因此请像一个准系统模板那样考虑。
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
export const LauncherButtons = [
{
linked: false,
type: "ABC",
name: "ReactJs"
},
{
linked: false,
type: "ABC",
name: "VueJS"
},
{
linked: true,
type: "XYZ",
name: "Angular"
},
{
linked: true,
type: "XYZ",
name: "Javascript"
}
];
class App extends React.Component {
state = {
buttons: LauncherButtons
};
createActiveButtons = () => {
const { buttons } = this.state;
return buttons
.filter(button => {
return button.linked;
})
.map(activeButton => {
return (
<button onClick={this.handleOnClick} name={activeButton.name}>
{activeButton.name}
</button>
);
});
};
createInactiveButtons = () => {
const { buttons } = this.state;
return buttons
.filter(button => {
return !button.linked;
})
.map(inactiveButton => {
return (
<button onClick={this.handleOnClick} name={inactiveButton.name}>
{inactiveButton.name}
</button>
);
});
};
handleOnClick = event => {
const { buttons } = this.state;
const { name } = event.target;
let updatedButtons = buttons.map(button => {
if (button.name === name) {
return {
...button,
linked: !button.linked
};
} else {
return button;
}
});
this.setState({
buttons: updatedButtons
});
};
render() {
return (
<div style={{ display: "flex" }}>
<div style={{ width: "50%", background: "green", height: "300px" }}>
{this.createActiveButtons()}
</div>
<div style={{ width: "50%", background: "red", height: "300px" }}>
{this.createInactiveButtons()}
</div>
</div>
);
}
}
答案 1 :(得分:0)
使用该项作为参数怎么办?例如:
removeAction(button) {
// change button however you like
}
// in the render method
{
LauncherButtons.map((button, index) => {
return (
button.linked &&
<LauncherActionButton
text={button.name}
onClick={() => removeAction(button)}/>
);
})
}