我试图在单击"是"或"否"时隐藏组件。点击时我得到了正确的输出,但像弹出菜单一样的组件保留在屏幕上,我无法删除它
这是我的组件
export default class MyPopUp extends React.Component {
constructor(props) {
super(props)
}
render() {
let { username } = this.props
return (
<div className="modal-wrapper">
<div className="modal">
Some Text
<br />
<MyButton
name={username}
surname="pewlas"
arguments={["yes"]}
>
[ Yes ]
</PostCommandButton>{" "}
<MyButton
name={username}
surname="pewlas"
arguments={["no"]}
>
[ No ]
</MyButton>{" "}
</div>
</div>
)
}
}
这是MyButton
import { connect } from "react-redux"
import button from "../../../common/components/Button"
import { myButton } from "../actions/myButton"
const MyButton = connect(
undefined,
(dispatch, { name, surname, arguments: args = [] }) => ({
onClick: () => dispatch(button(name, username, args)),
}),
)(Button)
export default MyButton
这是我的按钮
export const MY_BUTTON = "MY_BUTTON"
export const myButton = (name, surname, args) => ({
type: MY_BUTTON,
name,
surname,
arguments: args,
})
单击"是"或"否"时,如何隐藏MyPopUp
?我找不到将PopUp组件与来自MyButton的onClick链接的方法,我如何添加状态以便显示它?
我将尝试帮助您重构一些代码。
首先,我看到你正在使用redux与你的按钮,做你想做的事情你有一些选择:
const SURNAME = "pewlas"
export class MyPopUpComponent extends React.Component {
state = { hidden: false }
handleClick = value => {
this.props.myButton(this.props.username, SURNAME, value) //the action creator
this.setState({ hidden: true }) //**IMPORTANT**
}
render() {
const { username } = this.props
if (this.state.hidden) {
return null
}
return (
<div className="modal-wrapper">
<div className="modal">
Some Text
<br />
<button
name={username}
surname={SURNAME}
onClick={() => this.handleClick("yes")}
>
[ Yes ]
</button>{" "}
<button
name={username}
surname={SURNAME}
onClick={() => this.handleClick("no")}
>
[ No ]
</button>{" "}
</div>
</div>
)
}
}
const mapDispatchToProps = {
myButton
}
export const MyPopUp = connect(null, mapDispatchToProps)(MyPopUpComponent)
您可以这样做,首先,您显示隐藏为false的弹出初始化状态。正如您在渲染中看到的那样,您将使用按钮显示文本,一旦用户按下"是",或者现在您就可以启动操作或执行任何您想要的操作,然后将"隐藏"设置为true。状态已更改,因此再次调用呈现函数,返回null,从而隐藏组件。
希望它能帮助你